How to get an element at a specified index from a C ++ List

I have a list :

 list<Student>* l; 

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

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

Is there a function or method in list that allows this to be done?

+6
source share
4 answers

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'; // UB if v has less than 4 elements std::cout << v.at(4) << '\n'; // throws if v has less than 4 elements 
+8
source

Here's the get() function, which returns _i th Student to _list .

 Student get(list<Student> _list, int _i){ list<Student>::iterator it = _list.begin(); for(int i=0; i<_i; i++){ ++it; } return *it; } 
+2
source

If you need random access to elements, you must use vector , and then you can use the [] operator to get the 4th element.

 vector<Student> myvector (5); // initializes the vector with 5 elements` myvector[3]; // gets the 4th element in the vector 
+1
source

For std::vector you can use

myVector.at(i) // retrieve the i-th element

0
source

Source: https://habr.com/ru/post/945826/


All Articles