Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a value from a map?

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?

like image 729
Aneesh Narayanan Avatar asked May 22 '12 09:05

Aneesh Narayanan


People also ask

How do I find the value of a map without a key?

Check out the Map. entrySet() and Map. values() methods; those provide access to all values without having to provide a key.

How do you get a key value pair on a map?

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.


2 Answers

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.

like image 53
Steve Jessop Avatar answered Sep 28 '22 17:09

Steve Jessop


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/

like image 25
Gabe Rainbow Avatar answered Sep 28 '22 18:09

Gabe Rainbow