Related Articles

Related Articles

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

20

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.

My Personal Notes arrow_drop_up
Recommended Articles
Page :