[英]Iterate over map with pair as a key
I have a map with pair as a key and third integer as a value. 我有一个映射,其中pair作为键,第三个整数作为值。 I wonder how to iterate over keys.
我想知道如何迭代键。 Example code is pasted below.
示例代码粘贴在下面。
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
int main ()
{
map <pair<int, int>, int> my_map;
pair <int, int> my_pair;
my_pair = make_pair(1, 2);
my_map[my_pair] = 3;
// My attempt on iteration
for(map<pair<int,int>,int>::iterator it = my_map.begin(); it != my_map.end(); ++it) {
cout << it->first << "\n";
}
return 0;
}
it->first
is an object of type const std::pair<int, int>
that is it is the key. it->first
是const std::pair<int, int>
类型的对象,它是键。 it->second
is an object of type int
that is it is the mapped value. it->second
是int
类型的对象,它是映射值。 If you want simply to output the key and the mapped value you could write 如果您只想输出密钥和您可以编写的映射值
for ( map<pair<int,int>,int>::iterator it = my_map.begin(); it != my_map.end(); ++it )
{
cout << "( " << it->first.first << ", "
<< it->first.second
<< " ): "
<< it->second
<< std::endl;
}
Or you could use the range-based for statement 或者您可以使用基于范围的for语句
for ( const auto &p : my_map )
{
cout << "( " << p.first.first << ", "
<< p.first.second
<< " ): "
<< p.second
<< std::endl;
}
Well, map Key is first item, but itself it is a pair 好吧,map Key是第一项,但它本身就是一对
So 所以
pair<int,int>& key(*it);
cout << key.first << " " << key.second << "\n";
might do the trick 可能会做的伎俩
Do you have access to c++11, the auto keyword can make it look a lot nicer. 你有权访问c ++ 11,auto关键字可以让它看起来更好。 I compiled and ran this fine.
我编译并运行良好。
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
int main ()
{
map <pair<int, int>, int> my_map;
pair <int, int> my_pair;
my_pair = make_pair(1, 2);
my_map[my_pair] = 3;
// My attempt on iteration
for(auto it = my_map.begin(); it != my_map.end(); ++it) {
cout << it->first.first << "\n";
}
return 0;
}
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
map <pair<int, int>, int> my_map;
pair <int, int> my_pair;
my_pair = make_pair(1, 2);
my_map[my_pair] = 3;
// My attempt on iteration
for (map<pair<int, int>, int>::iterator it = my_map.begin(); it != my_map.end(); ++it) {
cout << it->first.first << "\n";
cout << it->first.second << "\n";
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.