user7554677
user7554677

Reputation:

Find value of index in Map Array using string key

In an array map<string, int> bannd such that each key (of type string) holds a number value, like this

+++++++++++++++
key   |  value
+++++++++++++++
red   |   0
blue  |   1
orange|   3

etc...

What is the optimal way to return the value of an index using the key?

I already tried using find like this

band1 = band.find("a");

where a is the key value in the map, but it does not seem to be working.

Upvotes: 0

Views: 6203

Answers (3)

Shravan40
Shravan40

Reputation: 9888

Write a function, which takes std::map and std::vector of key as argument. And it will return the corresponding values in std::vector

vector<int> valueReturn(map<string,int> data, vector<string> key) {
    vector<int> value;
    for(const auto& it: key) {
        auto search = data.find(it);
        if(search != data.end()) {
            value.push_back(data[it]);
            std::cout << "Found " << search->first << " " << search->second << '\n';
        }
        else {
            value.push_back(-1); // Inserting -1 for not found value, You can insert some other values too. Which is not used as value
            std::cout << "Not found\n";
        }
    }
    return value;
}

Upvotes: 0

Greg Kikola
Greg Kikola

Reputation: 573

find returns an iterator pointing to the found key-value pair (if any). You have to dereference that iterator to get the actual mapped value:

int band1;
auto it = band.find("a");
if (it != band.end())
  band1 = it->second;
else
  /* not found ... */;

Note that *it just gives us the std::pair containing the key and mapped value together. To access the mapped value itself we use it->second.

Alternatively, if you know that the key is in the map, you can use at to get the mapped value for that key:

int band1 = band.at("a");

at will throw an out_of_range exception if the element is not found.

Finally, if you want to access the value with key "a" and you want to automatically add that key to the map if it is not already there, you can use the subscript operator []:

int band1 = band["a"]; //warning: inserts {a, 0} into the map if not found!

Upvotes: 3

Brian
Brian

Reputation: 1210

int band1 = band["a"];
int band2 = band["b"];
int band3 = band["c"];
int band4 = band["d"];

Upvotes: -1

Related Questions