Calum Templeton
Calum Templeton

Reputation: 77

C++ Map get first element when second element is X

I have a C++ map called buttonValues as shown below.

map<int, int> buttonValues;

I put some data into my map as shown below.

buttonValues.insert(std::pair<int, int>(0, 1)); 
buttonValues.insert(std::pair<int, int>(1, 3)); 
buttonValues.insert(std::pair<int, int>(2, 0));

What I want to do is search for value 0 in the second column and if 0 is found in the second column, return the value in the first column. In this example, the value I would like to be returned is 2. So far I believe I can search for 0 in the second column with this:

buttonValues.find(0)->second

However, how do I get the value corresponding in the first column?

Thanks Calum

Upvotes: 2

Views: 12861

Answers (3)

qduyang
qduyang

Reputation: 363

Actually from performance's perspective, it is not suggested to search key by value from a map, the time complexity would be linear time O(N). If you search value by key from a map, it would be 'O(logN)'. You can consider to build a reverse map or multimap, or even unordered_map / unordered_multimap depends on your use case.

Upvotes: 0

Nikita Kozhevnikov
Nikita Kozhevnikov

Reputation: 11

Something like this:

for ( auto X : map_name )
  if ( X.second == 0 )
    return X.first;

std::pair<> holds values of first and second columns in your map. You can just iterate through all pairs and check second values for what you want.

Upvotes: 1

cantordust
cantordust

Reputation: 1612

buttonValues.find(0)->second will give you the value ("2nd column") corresponding to key 0. In your example, it will return 1. You need to iterate over the map and look for values = 0 and then return the key:

for (const auto& keyval : buttonValues) // Look at each key-value pair
{
    if (keyval.second == 0) // If the value is 0...
    {
        return keyval.first; // ...return the first element in the pair
    }
}

You can put this in a function. Note that a map has unique keys but not necessarily unique values. So you should probably handle the case where you have multiple keys for which the value is 0.

Upvotes: 3

Related Questions