Get Map Element at Offset in C++ STL
Last Updated :
08 Dec, 2022
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
1. Using an iterator to begin() and offset
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++
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< char , int > m;
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;
while (k < offset) {
k++;
itr++;
}
cout << itr->first << " " << itr->second << endl;
}
|
2. Using advance() function
Using the advance function the offset is given directly and it directly moves the iterator to the particular offset in the map.
Syntax:
advance(begin_itr,offset)
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< char , int > m;
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();
advance(itr, offset);
cout << itr->first << " " << itr->second << endl;
}
|
3. Using the next() function
The next() function can be used which takes the beginning iterator and the offset. The return value of the next() function is the pointer to the key-value pair at the particular offset.
Syntax:
next(begin_itr, offset)
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< char , int > m;
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();
auto nitr = next(itr, offset);
cout << nitr->first << " " << nitr->second << endl;
}
|
Share your thoughts in the comments
Please Login to comment...