我正在寻找一种以 FIFO 顺序(先进先出)对 C++ 映射进行排序的方法
在 FIFO 中,我们假设一个元素将在开头插入,删除操作将在结尾处进行。
因此,如果我们假设当前代码是用于对 map 进行排序的比较器
结构类comp {
bool operator() (const char& lhs, const char& rhs) const
{返回假;}
};
如果我们假设第一个元素是 map 中的现有元素,当第二个元素是要插入的元素时,我的 map 是否有可能按 FIFO 顺序排序?
谢谢,
最佳答案
我时不时遇到同样的问题,这是我的解决方案:https://github.com/nlohmann/fifo_map .它是一个仅包含 header 的 C++11 解决方案,可用作 std::map
的直接替代品。
例子
#include "src/fifo_map.hpp"
// for convenience
using nlohmann::fifo_map;
int main() {
// create fifo_map with template arguments
fifo_map<int, std::string> m;
// add elements
m[2] = "two";
m[3] = "three";
m[1] = "one";
// output the map; will print
// 2: two
// 3: three
// 1: one
for (auto x : m) {
std::cout << x.first << ": " << x.second << "\n";
}
// delete an element
m.erase(2);
// re-add element
m[2] = "zwei";
// output the map; will print
// 3: three
// 1: one
// 2: zwei
for (auto x : m) {
std::cout << x.first << ": " << x.second << "\n";
}
}
请注意 fifo_map
的元素如何始终按插入顺序打印。
关于c++ - 如何按 FIFO 顺序对 C++ 映射进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25272478/