Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over map and use the pair as reference parameter C++11

I have an std::map. and I would like to iterate over it and use the result as an argument to a function. The compilation seems to complain about my object being a lvalue, but I cannot figure out why it is considered as a lvalue.

void my_function(std::pair<std::string, std::string>& my_arg){
    //do stuff, modify elements from the pair
}

std::map<std::string, std::string> my_map;
// fill the map with values...

for(auto& element : my_map){
    my_function(element);
}

I could probably use an iterator to solve this, but I would like to learn how to do it the c++11 way.

like image 483
Snemed Avatar asked Jun 22 '18 11:06

Snemed


2 Answers

The value_type of std::map and its iterator is std::pair<const std::string, std::string> and not std::pair<std::string, std::string>. In other words keys are always constant in C++ maps.

like image 87
navyblue Avatar answered Oct 05 '22 23:10

navyblue


std::map<std::string, std::string>::value_type is std::pair<const std::string, std::string>: note the const. If you were allowed to modify the key within a pair, that might violate the invariant that the map's entries are sorted by key. Since you used a different pair type, the reference can't bind to the actual object.

like image 43
aschepler Avatar answered Oct 06 '22 01:10

aschepler