Skip to content
Related Articles

Related Articles

Improve Article

How to get element at specific position in List in C++

  • Difficulty Level : Easy
  • 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++




// C++ program to access  Kth element
// of the list using advanced
#include <bits/stdc++.h>
using namespace std;
  
// Driver Code
int main()
{
    // Create list with initial value 100
    list<int> li(5, 100);
  
    // Insert 20 and 30 to the list
    li.push_back(20);
    li.push_back(30);
  
    // Elements of list are
    // 100, 100, 100, 100, 100, 20, 30
  
    // Initialize iterator to list
    list<int>::iterator it = li.begin();
  
    // Move the iterator by 5 elements
    advance(it, 5);
  
    // Print the element at the it
    cout << *it;
  
    return 0;
}
Output:
20
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :