check if map contains a certain value

Advertisements

Hello I am currently facing a problem or maybe I thinking too complicated.

I have a map that looks like this:

  std::map<int,int> mymap;

and I insert values doing this

 std::map<char,int>::iterator it = mymap.begin();
  mymap.insert (it, std::pair<int,int>(1,300));  

now I want to find out if the map contains the value 300.

Lets assume I have a variable called input with the value 300.

int input = 300;

Now with this input I want to check whether my map has the value 300 stored in it.

I know that with map.find() I can check whether a certain key exists in a map.
But I can’t use map.find(input) in my case because 300 isn’t the key it’s the value.

How can I check whether there is a value of 300 in my map?

>Solution :

You can use std::find_if to find if a value exists in a std::map or not shown below:

#include <iostream>
#include <map>
#include <string>
 #include <algorithm>

int main()
{
    // Create a map of three strings (that map to integers)
    std::map<int, int> m { {1, 10}, {2, 15}, {3, 300}, };
    
   int value = 300;
   auto result = std::find_if(std::begin(m), std::end(m), [value](const auto& mo) {return mo.second == value; });
 
   if(result != std::end(m))
   {
       std::cout<<"found"<<std::endl;
   }
    else 
    {
        std::cout<<"not found"<<std::endl;
    }
}

The output of the above program can be seen here.

Leave a ReplyCancel reply