How to get an element at specified index from c++ List

std::list does not have a random access iterator, so you have to step 4 times from the front iterator. You can do this manually or with std::advance, or std::next in C++11, but bear in mind that both O(N) operations for a list.

#include <iterator>
#include <list>

....

std::list<Student> l; // look, no pointers!
auto l_front = l.begin();

std::advance(l_front, 4);

std::cout << *l_front << '\n';

Edit: The original question asked about vector too. This is now irrelevant, but may be informative nonetheless:

std::vector does have random access iterators, so you can perform the equivalent operation in O(1) via the std::advance, std::next if you have C++11 support, the [] operator, or the at() member function:

std::vector<Student> v = ...; 
std::cout << v[4] << '\n';    // UB if v has less than 4 elements
std::cout << v.at(4) << '\n'; // throws if v has less than 4 elements

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)