c++ - 如果用作映射中的键,如何获取对的第一个和第二个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29560245/
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
c++ - How to get first and second element of pair if used as key in map?
提问by chota bheem
I was trying to get first and second element of pair when i am using pair as key in map.For better clarification please see code below.This is what i have tried
当我在地图中使用 pair 作为键时,我试图获取 pair 的第一个和第二个元素。为了更好的说明,请参阅下面的代码。这是我尝试过的
#include <bits/stdc++.h>
using namespace std;
int main()
{
// your code goes here
map<pair<int,int>,int>mp;
int n;
cin>>n;
int a[n];
for(int i=0;i<n;++i)cin>>a[i];
int y=0;
for(int i=0;i<n;++i)
{
mp.insert(make_pair(y,a[i]));
y=a[i]+1;
}
int m;
cin>>m;
int q[m];
for(int i=0;i<m;++i)cin>>q[i];
for(int i=0;i<m;i++)
{
int temp=q[i];
for(map<pair<int,int>,int>::iterator it=mp.begin();it!=mp.end();++it)
{
if(((it->first)<=temp)&&((it->second)>=temp))
cout<<mp->second<<endl;
}
}
return 0;
}
I want to get first and second element of key here.How can i do that ?
我想在这里获得关键的第一个和第二个元素。我该怎么做?
回答by Cory Kramer
When you iterate over your map
, you can get the following items
当您迭代您的 时map
,您可以获得以下项目
std::pair<int, int> key = it->first;
int value = it->second;
Therefore the first
and second
value of the key
would be
因此first
和 的second
价值key
将是
it->first.first;
it->first.second;