C++ 在 map<pair, int> 上使用 find

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11246606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:58:51  来源:igfitidea点击:

Using find on map<pair, int>

c++dictionary

提问by Jon

How do you use find with a const_iteratorif you have a map defined as

const_iterator如果您将地图定义为,您如何使用 find 和 a

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

with the pairdefined as the key.

pair定义为键。

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

如果只是map<int, int>,我知道如何使用const_iterator

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

// etc..

回答by Jon

If you are not using C++11, the most convenient is to also do a typedeffor the map type:

如果你没有使用 C++11,最方便的是也typedef为 map 类型做一个:

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 intis not compatible with your map).

(我还更改了传递给 的参数find,因为裸int图与您的地图不兼容)。

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

如果您使用的是 C++11,您也可以简单地做

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

回答by Chad

Find takes a key type of your map, so in this case you need to create a std::pairthat you want to use in the lookup. Here's a short example:

Find 采用地图的键类型,因此在这种情况下,您需要创建std::pair要在查找中使用的类型。这是一个简短的例子:

#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";
   }
}

回答by Debasis

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";
   }
}

回答by EnzoGuerra

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"));