I have a map
named valueMap
as follows:
typedef std::map<std::string, std::string>MAP; MAP valueMap; ... // Entering data.
Then I am passing this map to a function by reference:
void function(const MAP &map) { std::string value = map["string"]; // By doing so I am getting an error. }
How can I get the value from the map, which is passed as a reference to a function?
Check out the Map. entrySet() and Map. values() methods; those provide access to all values without having to provide a key.
To get the key and value elements, we should call the getKey() and getValue() methods. The Map. Entry interface contains the getKey() and getValue() methods. But, we should call the entrySet() method of Map interface to get the instance of Map.
std::map::operator[]
is a non-const member function, and you have a const reference.
You either need to change the signature of function
or do:
MAP::const_iterator pos = map.find("string"); if (pos == map.end()) { //handle the error } else { std::string value = pos->second; ... }
operator[]
handles the error by adding a default-constructed value to the map and returning a reference to it. This is no use when all you have is a const reference, so you will need to do something different.
You could ignore the possibility and write string value = map.find("string")->second;
, if your program logic somehow guarantees that "string"
is already a key. The obvious problem is that if you're wrong then you get undefined behavior.
map.at("key")
throws exception if missing key.
If k does not match the key of any element in the container, the function throws an out_of_range exception.
http://www.cplusplus.com/reference/map/map/at/
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