Reputation: 1071
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);
?
Upvotes: 107
Views: 330489
Reputation: 124
Not very efficient, but if you must use a list, you can deference the iterator
*myList.begin()+N
Upvotes: 0
Reputation: 6647
Maybe not the most efficient way. But you could convert the list into a vector.
#include <list>
#include <vector>
list<Object> myList;
vector<Object> myVector(myList.begin(), myList.end());
Then access the vector using the [x] operator.
auto x = MyVector[0];
You could put that in a helper function:
#include <memory>
#include <vector>
#include <list>
template<class T>
shared_ptr<vector<T>>
ListToVector(list<T> List) {
shared_ptr<vector<T>> Vector {
new vector<string>(List.begin(), List.end()) }
return Vector;
}
Then use the helper funciton like this:
auto MyVector = ListToVector(Object);
auto x = MyVector[0];
Upvotes: 3
Reputation: 361672
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
Upvotes: 40
Reputation: 142919
std::list<Object> l;
std::list<Object>::iterator ptr;
int i;
for( i = 0 , ptr = l.begin() ; i < N && ptr != l.end() ; i++ , ptr++ );
if( ptr == l.end() ) {
// list too short
} else {
// 'ptr' points to N-th element of list
}
Upvotes: 9
Reputation: 355207
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.
Upvotes: 145