How to get element at specific position in List in C++
Last Updated :
01 Dec, 2020
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. Instead of iterating for K times. For this, an STL std::advance() function is used to find it in linear time.
Syntax:
advance(InputIterator& it, Distance N)
Parameters: This function accepts two parameters i.e., iterator that is to be traversed through the list and the position to where it has to be moved. The position can be negative for random access and bidirectional iterators.
Return Type: This function has no return type.
Below is the C++ implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
list< int > li(5, 100);
li.push_back(20);
li.push_back(30);
list< int >::iterator it = li.begin();
advance(it, 5);
cout << *it;
return 0;
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...