I am currently learning about maps in STL. I want to know how to get a specific key value pair from the map. For example, 3rd key-value pair from the map below. 'C'-> 1
'A'-> 1
'B'-> 1
'C'-> 1
'D'-> 1
'E'-> 2
I am currently learning about maps in STL. I want to know how to get a specific key value pair from the map. For example, 3rd key-value pair from the map below. 'C'-> 1
'A'-> 1
'B'-> 1
'C'-> 1
'D'-> 1
'E'-> 2
Yes, we can access "The third key-value pair" of a map, but it's not very straightforward. We need to get an iterator the beginning of the map and then advance it twice (note, that in more generic code you should check that the map has the appropriate size before doing something like this)
std::map<char, int> my_map;
my_map['C'] = 3;
my_map['A'] = 1;
my_map['B'] = 2;
auto begin = my_map.begin();
std::advance(begin, 2);
std::cout << begin->first << " : " << begin->second << std::endl;
Output:
C : 3
Note that the 3rd element is actually the first key-value pair we inserted. This is because keys are inserted in sorted order.
If I have understood you correctly you need something like
#include <iostream>
#include <map>
#include <iterator>
int main()
{
std::map<char, unsigned int> m =
{
{ 'A', 1 }, { 'B', 1 }, { 'C', 1 }, { 'D', 1 }, { 'E', 2 }
};
auto it = std::next( std::begin( m ), std::min<decltype( m )::size_type>( m.size(), 2 ) );
if ( it != std::end( m ) )
{
std::cout << it->first << ": " << it->second << '\n';
}
return 0;
}
The program output is
C: 1
That is you can use operations with iterators.
Or maybe you need to use just the method find
of the class as for example
#include <iostream>
#include <map>
#include <iterator>
int main()
{
std::map<char, unsigned int> m =
{
{ 'A', 1 }, { 'B', 1 }, { 'C', 1 }, { 'D', 1 }, { 'E', 2 }
};
auto it = m.find( 'C' );
if ( it != std::end( m ) )
{
std::cout << it->first << ": " << it->second << '\n';
}
return 0;
}
Again the program output is
C: 1