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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…