And*_*rej 4 c++ dictionary iterator stdmap output
我有一个映射,其中pair作为键,第三个整数作为值.我想知道如何迭代键.示例代码粘贴在下面.
#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;
}
Run Code Online (Sandbox Code Playgroud)
it->first
是一个类型的对象,const std::pair<int, int>
它是关键.it->second
是一个类型的对象,int
它是映射的值.如果您只想输出密钥和您可以编写的映射值
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;
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用基于范围的for语句
for ( const auto &p : my_map )
{
cout << "( " << p.first.first << ", "
<< p.first.second
<< " ): "
<< p.second
<< std::endl;
}
Run Code Online (Sandbox Code Playgroud)
好吧,map Key 是第一项,但它本身是一对
所以
pair<int,int>& key(*it);
cout << key.first << " " << key.second << "\n";
Run Code Online (Sandbox Code Playgroud)
可能会成功