std::list does not have a random access iterator, so you need to do step 4 from the front iterator. You can do this manually or using std :: advance or std :: next in C ++ 11, but keep in mind that both operations are O (N) for the 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';
Change An original question was asked about the vector. It doesnβt matter now, but it can be informative, though:
std::vector has random access iterators, so you can perform an equivalent operation in O (1) with std::advance , std :: next if you have C ++ 11 support, the [] operator or the member function at() :
std::vector<Student> v = ...; std::cout << v[4] << '\n';
source share