Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a certain element in a list, given the position?

Tags:

c++

list

stl

So I've got a list:

list<Object> myList; myList.push_back(Object myObject); 

I'm not sure but I'm confident that this would be the "0th" element in the array. Is there any function I can use that will return "myObject"?

Object copy = myList.find_element(0); 

?

like image 709
Test Avatar asked Apr 20 '11 16:04

Test


People also ask

How do you get a specific value from a list in C++?

How to get element at specific position in List in C++ The list doesn't have random access operator [] to access elements by indices, because std::list internally store elements in a doubly-linked list. So, to access an element at any Kth location, the idea is to iterate one by one from beginning to Kth element.

How do you get the position of an element in a list in Java?

The indexOf(Object) method of the java. util. ArrayList class returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Using this method, you can find the index of a given element.


2 Answers

If you frequently need to access the Nth element of a sequence, std::list, which is implemented as a doubly linked list, is probably not the right choice. std::vector or std::deque would likely be better.

That said, you can get an iterator to the Nth element using std::advance:

std::list<Object> l; // add elements to list 'l'...  unsigned N = /* index of the element you want to retrieve */; if (l.size() > N) {     std::list<Object>::iterator it = l.begin();     std::advance(it, N);     // 'it' points to the element at index 'N' } 

For a container that doesn't provide random access, like std::list, std::advance calls operator++ on the iterator N times. Alternatively, if your Standard Library implementation provides it, you may call std::next:

if (l.size() > N) {     std::list<Object>::iterator it = std::next(l.begin(), N); } 

std::next is effectively wraps a call to std::advance, making it easier to advance an iterator N times with fewer lines of code and fewer mutable variables. std::next was added in C++11.

like image 66
James McNellis Avatar answered Sep 23 '22 09:09

James McNellis


std::list doesn't provide any function to get element given an index. You may try to get it by writing some code, which I wouldn't recommend, because that would be inefficient if you frequently need to do so.

What you need is : std::vector. Use it as:

std::vector<Object> objects; objects.push_back(myObject);  Object const & x = objects[0];    //index isn't checked Object const & y = objects.at(0); //index is checked  
like image 25
Nawaz Avatar answered Sep 23 '22 09:09

Nawaz