如何以一对为键遍历地图

How can I iterate over a map with a pair as key?

本文关键字:遍历 地图      更新时间:2023-10-16

我有一个mappair<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->firstconst 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;
}