C++ 使用 pair<int, int> 作为映射的键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15016646/
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 18:53:41  来源:igfitidea点击:

Using pair<int, int> as key for map

c++mapstd-pair

提问by sccs

Based on a previous question, I am trying to create a map using a pair of integers as a key i.e. map<pair<int, int>, int>and I've found information on how to insert:

基于上一个问题,我正在尝试使用一对整数作为键创建一个映射,即map<pair<int, int>, int>我找到了有关如何插入的信息:

#include <iostream>
#include <map>

using namespace std;

int main ()
{
map<pair<int, int>, int> mymap;

mymap.insert(make_pair(make_pair(1,2), 3)); //edited
}   

but I can't seem to access the element! I've tried cout << mymap[(1,2)] << endl;but it shows an error, and I can't find information on how to access the element using the key. Am I doing something wrong?

但我似乎无法访问该元素!我已经尝试过,cout << mymap[(1,2)] << endl;但它显示了一个错误,而且我找不到有关如何使用密钥访问元素的信息。难道我做错了什么?

采纳答案by andre

you need a pair as a key cout << mymap[make_pair(1,2)] << endl;What you currently have cout << mymap[(1,2)] << endl;is not the correct syntax.

您需要一对作为键cout << mymap[make_pair(1,2)] << endl;您目前拥有cout << mymap[(1,2)] << endl;的语法不正确。

回答by Louis Brandy

mymap[make_pair(1,2)]

mymap[make_pair(1,2)]

or, with compiler support:

或者,在编译器支持下:

mymap[{1,2}]

mymap[{1,2}]

回答by Chandra Shekhar

Please find the code for the reference:

请找到参考代码:

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


int main()
{

   map<pair<int ,int> ,int > m;
   m.insert({{1, 2}, 100});
   cout << m[{1, 2}];
}