How to use an iterator to begin() and offset In C++
The iterator to the begin() is incremented until it reaches the offset using the while loop and then the key-value pair is printed.
C++
// C++ Program to Get // Map Element At Offset // using iterator to begin() // and offset #include <bits/stdc++.h> using namespace std; int main() { // Declaring a map with char ,int map< char , int > m; // Adding pairs into the map m.insert({ 'a' , 3 }); m.insert({ 'g' , 2 }); m.insert({ 'f' , 4 }); m.insert({ 'e' , 5 }); m.insert({ 'd' , 4 }); m.insert({ 'b' , 3 }); int offset = 3; auto itr = m.begin(); int k = 0; // Iterate while k is <offset while (k < offset) { k++; itr++; } // print the key value pair at offset cout << itr->first << " " << itr->second << endl; } |
e 5
Get Map Element at Offset in C++ STL
Prerequisites: Map in C++ STL
Since the map is not indexed as arrays or vectors sequential access is not possible in the map but to access an element at a particular offset.
Example:
inserted elements are { ‘a’,11 } , { ‘b’,12 } , { ‘ c ‘, 13 }
then we can get { ‘b’, 12 } for 2 position.
Methods to Get Map Element at Offset in C++ STL
- Using an iterator to begin() and offset
- Using advance() function
- Using the next() function