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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With