To insert an element at a specific index in a list in C++ using std::list
, you can use the std::advance
and std::insert
functions.
In this example,
and
.std::list
named numbers
with initial integer values.std::advance
function to move the iterator to the desired index.std::insert
function to insert the new element at the iterator position.#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5};
int index = 2;
int element = 10;
auto it = numbers.begin();
std::advance(it, index);
numbers.insert(it, element);
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
1 2 10 3 4 5
In this example,
and
.std::list
named numbers
with initial integer values.std::insert
function to insert a new element at the beginning of the list.#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5};
int element = 10;
numbers.insert(numbers.begin(), element);
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
10 1 2 3 4 5
In this tutorial, we learned How to Insert an Element at Specific Index in a List in C++ language with well detailed examples.