To remove an element at a specific index from a list in C++ using `std::list`, you can use the `std::advance` function in combination with the `std::list::iterator`.
In this example,
myList
with some elements.it
and advance it to the desired index using the std::advance
function.erase
method of the list to remove the element at the iterator position.#include <iostream>
#include <list>
#include <iterator>
int main() {
std::list<int> myList = {1, 2, 3, 4, 5};
int index = 2;
auto it = myList.begin();
std::advance(it, index);
myList.erase(it);
for (auto& element : myList) {
std::cout << element << " ";
}
return 0;
}
1 2 4 5
In this example,
myList
with some elements.pop_back
method of the list to remove the element at the last index.#include <iostream>
#include <list>
int main() {
std::list<int> myList = {1, 2, 3, 4, 5};
myList.pop_back();
for (auto& element : myList) {
std::cout << element << " ";
}
return 0;
}
1 2 3 4
In this tutorial, we learned How to Remove Element at a Specific Index from a List in C++ language with well detailed examples.