To access an element in a std::list at a specific index in C++, you can use the std::advance function with an iterator.
In this example,
numbers
with integer elements.it
and advance it to the desired index using std::advance
.*it
.#include <iostream>
#include <list>
#include <iterator>
int main() {
std::list<int> numbers = {10, 20, 30, 40, 50};
auto it = numbers.begin();
std::advance(it, 2);
std::cout << "Element at index 2 is: " << *it << std::endl;
return 0;
}
Element at index 2 is: 30
In this tutorial, we learned How to get Element in a List at a Specific Index in C++ language with well detailed examples.