如何以一对为键遍历地图
How can I iterate over a map with a pair as key?
我有一个map
,pair<int, int>
作为键,第三个整数作为值。如何迭代地图的键以打印它们?我的示例代码粘贴如下:
#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;
}
如何修改cout
行,使其正常工作?
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;
}
或者您可以使用基于范围的 for 语句
for ( const auto &p : my_map )
{
cout << "( " << p.first.first << ", "
<< p.first.second
<< " ): "
<< p.second
<< std::endl;
}
好吧,地图键是第一项,但它本身是一对
所以
pair<int,int>& key(*it);
cout << key.first << " " << key.second << "n";
可能会解决问题
您是否可以访问c ++ 11,auto 关键字可以使它看起来更好。我编译并运行得很好。
#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;
}
默认情况下,std::ostream
不知道如何处理std::pair
。因此,如果您想打印密钥,最简单的方法是直接访问它们的两个元素,如其他答案所示。但是,如果您有权访问 C++11 要素,则还可以使用基于范围的for
循环来迭代地图,如下所示:
int main() {
std::map<std::pair<int, int>, int> my_map{ {{1, 2}, 3}, {{4, 5}, 6}, {{7, 8}, 9} };
for (auto const &kv : my_map)
std::cout << "(" << kv.first.first << ", " << kv.first.second << ") = " << kv.second << std::endl;
return 0;
}
输出:
(1, 2) = 3
(4, 5) = 6
(7, 8) = 9
如果可以使用 C++17,则可以使用结构化绑定进一步缩短代码在基于范围的for
循环中,如下所示:
for (auto const &[k, v] : my_map)
std::cout << "(" << k.first << ", " << k.second << ") = " << v << std::endl;
科里鲁密码
#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;
}
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 从特定键开始遍历地图
- 如何遍历多个地图并获取它们的值? - C++
- 如何在C++中遍历谷歌原型地图?
- 如何遍历地图向量
- 遍历地图并将该对用作参考参数 C++11
- 使用相同的 for 循环按升序或降序遍历地图
- 如何遍历成对值的地图?
- 循环遍历地图时编译错误
- C++ - 遍历地图的地图
- 如何以一对为键遍历地图
- "No match for operator="尝试在C++中遍历地图
- 帮助提高地图遍历 C++ 的效率