1

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Sharik Sid
  • 109
  • 2
  • 9

2 Answers2

6

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

Live Demo

Note that the 3rd element is actually the first key-value pair we inserted. This is because keys are inserted in sorted order.

Community
  • 1
  • 1
AndyG
  • 39,700
  • 8
  • 109
  • 143
  • 1
    Mind that if you don't want to access data by key, you should consider an other, more accurate, container. [Here](https://stackoverflow.com/questions/471432/in-which-scenario-do-i-use-a-particular-stl-container) you can find a chart which will help to choose an accurate container for this scenario. – DrosvarG May 28 '19 at 14:28
  • Thank you so much. I got a hang of it now. – Sharik Sid May 28 '19 at 14:34
1

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335