c++ - 如何按 FIFO 顺序对 C++ 映射进行排序?

标签 c++ sorting dictionary

我正在寻找一种以 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/

相关文章:

c++ - GCC 有内置的编译时断言吗?

c++ - 如何在声明的模块外使用 wxTheApp 宏?

c++ - 当更新发生时如何使用 lib_mysqludf_sys 执行外部程序?

python - 将 2D numpy.ndarray 转换为嵌套字典

c# - 对从托管代码创建的事件的 WaitForSingleObject 访问被拒绝

javascript - 有什么方法可以扩展 javascript 的 array.sort() 方法以接受另一个参数?

linux - Bash 排序忽略前 5 行

java - 为什么该表将所有条目按字符串排序?

python:以灵活的方式处理深度嵌套数据的有效技术是什么?

python - 如何按版本键对字典进行排序