Home > Software engineering >  get reference to a node of std::map using key
get reference to a node of std::map using key

Time:05-31

How to get reference to a node of std::map using key std::pair<key_type, value_type>& node = map_obj[key];. I know operator[] of std::map returns reference to value part, but I want reference to entire node (std::pair<key_type, value_type>&).

CodePudding user response:

You can use the following. Of course, this snippet assumes that the key exists in the map (i.e. mymap.find("b") != mymap.end()). Also, the first member of the pair has to be constant (as changing its values would invalidate the map).

#include <iostream>
#include <map>

int main()
{
    std::map<std::string, int> mymap = {{"a",5}, {"b", 7}};

    std::pair<const std::string, int> &mypair = *mymap.find("b");
    std::cout << mypair.first<< " " << mypair.second << std::endl;
    return 0;
}

CodePudding user response:

You have the key already. Just form a pair :

std::pair<key_type, value_type>& ref = {key, map_obj[key]}; 
  •  Tags:  
  • c
  • Related