7

How do you use find with a const_iterator if you have a map defined as

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

with the pair defined as the key.

If it was just map<int, int>, I know how to use a const_iterator like

typedef map<int, int> MyMap;
MyMap::const_iterator it = 
      MyMap.find(0);

// etc..
Marek R
  • 32,568
  • 6
  • 55
  • 140

4 Answers4

10

If you are not using C++11, the most convenient is to also do a 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, as a bare int is not compatible with your map).

If you are using C++11, you can also do simply

auto it = MyMap.find(make_pair(0, 0));
Jon
  • 428,835
  • 81
  • 738
  • 806
4

Find takes a key type of your map, so in this case you need to create a std::pair that you want to use in the lookup. Here's a short 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";
   }
}
Chad
  • 18,706
  • 4
  • 46
  • 63
0

There compilation issue in the above code. Please find the correct one as below:

#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

think you could use

std::map<std::pair<int, int>, std::string> m = {
    {{ 0, 0 }, "Hello" },
    {{ 1, 0 }, "There" },
 };

instead of

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