Using find on map <pair, int>

How do you use find with const_iterator

if you have a map defined as

typedef std::pair<int, int> MyPair;

map<MyPair, int> MyMap;

with pair

defined as a key.

If it was simple map<int, int>

I know how to use const_iterator

like

typedef map<int, int> MyMap;

MyMap::const_iterator it = MyMap.find(0);

etc..

+1


source to share


3 answers


If you are not using C ++ 11 , the most convenient is also the type typedef

for the map type:

typedef std::map<MyPair, int> map_type;

      

And then

map_type::const_iterator it = MyMap.find(make_pair(0, 0));

      



(I also changed the parameter passed to find

, since bare is int

not compatible with your card).

If you are using C ++ 11 you can also just

auto it = MyMap.find(make_pair(0, 0));

      

+4


source


The search takes the key type of your map, so in this case you need to create the std::pair

one you want to use in the search. Here's a quick example:



#include <map>
#include <string>
#include <iostream>
using namespace std;

int main()
{
   std::map<std::pair<int, int>, std::string> m;

   m.insert(make_pair(make_pair(0, 0), "Hello"));
   m.insert(make_pair(make_pair(1, 0), "There"));

   auto res = m.find(make_pair(0,0));

   if(res != m.end())
   {
      cout << res->second << "\n";
   }
}

      

+2


source


There is a compilation issue in the above code. Please find the correct one:

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

using namespace std;

int main()
{
   std::map<std::pair<int, int>, std::string> m;
   std::map<std::pair<int, int>, std::string>::iterator res;

   m.insert(std::make_pair(make_pair(0, 0), "Hello"));
   m.insert(std::make_pair(make_pair(1, 0), "There"));

   res = m.find(make_pair(0,0));

   if(res != m.end())
   {
      cout << res->second << "\n";
   }
}

      

0


source







All Articles