Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have a list:

list<Student>* l; 

and I would like to get an element at a specified index. Example:

l->get(4)//getting 4th element 

Is there a function or method in list which enables it to do so?

like image 266
user2398815 Avatar asked May 25 '13 07:05

user2398815


People also ask

How do you find the nth element of a list in C++?

Accessing nth element in std::list using std::next() ForwardIterator next (ForwardIterator it, typename iterator_traits<ForwardIterator>::difference_type n = 1); template <class ForwardIterator> ForwardIterator next (ForwardIterator it, typename iterator_traits<ForwardIterator>::difference_type n = 1);


1 Answers

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 
like image 91
juanchopanza Avatar answered Sep 27 '22 18:09

juanchopanza