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?
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With