0

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?

konoha
  • 57
  • 1
  • 8
  • 1
    The only way to do this would be to iterate over the entire map. – Tyler Liu Nov 28 '21 at 19:04
  • @TylerLiu then in this case my key is kind of unnecessary am I right? because I won't be needing it when iterating over the whole map – konoha Nov 28 '21 at 19:06
  • Also you can add another map that maps values to keys. – ks1322 Nov 28 '21 at 19:08
  • 1
    @konoha Hard to say without knowing more context. Double check that a map is really what you need instead of a list. What purpose does the key serve in this case? What is it representing? – Tyler Liu Nov 28 '21 at 19:11
  • https://www.geeksforgeeks.org/search-by-value-in-a-map-in-c/amp/ – Gokul Nath KP Nov 28 '21 at 19:11
  • @TylerLiu the amount of users. so user has input of 300 and if there were more users the map would look like this 1 300, 2 400, 3 600 etc – konoha Nov 28 '21 at 19:15
  • If you are doing this frequently [boost bimap](https://www.boost.org/doc/libs/1_77_0/libs/bimap/doc/html/index.html) or [boost multi index](https://www.boost.org/doc/libs/1_40_0/libs/multi_index/doc/index.html) might be better options – Alan Birtles Nov 28 '21 at 19:18

1 Answers1

2

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.

Jason
  • 36,170
  • 5
  • 26
  • 60