c++ - 使用 iter_swap 交换 map 中的元素

标签 c++

我有一个“简单”的问题: 我正在尝试交换 map 中的对以更改顺序。 此代码无法编译。

#include <iostream>
#include <string>
#include <map>
#include <algorithm>

int main()
{
  std::map<std::string, int> map;
  map.insert({"one", 1});  
  map.insert({"two", 2});  
  map.insert({"three", 3});

  for(const auto& e :map)
  {
    std::cout << e.first << " " << e.second << std::endl;   
  }

  std::iter_swap(map.begin(), map.rbegin());

  for(const auto& e :map)
  {
    std::cout << e.first << " " << e.second << std::endl;   
  }
}

这可能吗?我该怎么做?

最佳答案

Is it possible

这是不可能的。映射的元素按照比较函数建立的顺序排列。元素不能交换。

如果你想要一个可以选择对顺序的结构,你可以使用 std::vector<std::pair<std::string, int>>反而。如果您想要快速查找和任意顺序,那么您需要一个多索引数据结构。标准库没有这样的容器。然而,Boost 确实如此。

关于c++ - 使用 iter_swap 交换 map 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59397039/

相关文章:

c++ - MingW C++ 编译器不工作

C++在成员变量中保存不同类型数据的优雅方式

c++ - 使用从列表中弹出的 pthreads 填充大小的列表

c++ - 为什么此模板代码中需要 static 关键字?

c++ - GCC在被杀死时创建带有随机后缀的目标文件

c# - C++文本文件读取性能

c++ - *this = NULL 在模板类的方法中意味着什么?

c++ - SDL + SDL_ttf : Transparent blended text?

c++ - A*寻路找到玩家需要走的路径,Qt中的c++

c++ - WebRTC 原生 c++ 应用程序作为 win10 服务无法访问视频源