c++ - 保留插入顺序的 C++ HashMap

标签 c++ unordered-map html-lists multi-index

<分区>

我有以下代码:

#include <iostream>
#include "boost/unordered_map.hpp"

using namespace std;
using namespace boost;

int main()
{

    typedef unordered_map<int, int> Map;
    typedef Map::const_iterator It;

    Map m;
    m[11] = 0;
    m[0]  = 1;
    m[21] = 2;

    for (It it (m.begin()); it!=m.end(); ++it)
        cout << it->first << " " << it->second << endl;

    return 0;
}

但是,我正在寻找保留顺序的东西,以便以后我可以按照插入元素的相同顺序遍历元素。在我的电脑上,上面的代码不保留顺序,并打印以下内容:

 0 1
11 0
21 2

我想也许我可以使用 boost::multi_index_container

typedef multi_index_container<
    int,
    indexed_by<
        hashed_unique<identity<int> >,
        sequenced<>
    >
> Map;

有人可以告诉我如何使用这个容器(或任何其他合适的容器)实现我的原始代码,以便迭代器遵循插入顺序吗?

最佳答案

#include <iostream>
#include "boost/unordered_map.hpp"

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>

using namespace std;
using namespace boost;
using namespace boost::multi_index;


struct key_seq{};
struct key{};

struct Data_t
{
    int key_;
    int data_;
    Data_t (int key_v, int data_v) : key_(key_v), data_(data_v) {}
};

int main()
{
    typedef multi_index_container<
        Data_t,
        indexed_by<
            hashed_unique<tag<key>,  BOOST_MULTI_INDEX_MEMBER(Data_t,int,key_)>,
            sequenced<tag<key_seq> >
        >
    > Map;

    typedef Map::const_iterator It;

    typedef index<Map,key>::type Map_hashed_by_key_index_t;
    typedef index<Map,key>::type::const_iterator  Map_hashed_by_key_iterator_t;

    typedef index<Map,key_seq>::type Map_sequenced_by_key_index_t;
    typedef index<Map,key_seq>::type::const_iterator  Map_sequenced_by_key_iterator_t;

    Map m;
    m.insert(Data_t(11,0));
    m.insert(Data_t(0,1));
    m.insert(Data_t(21,1));

    {
        cout << "Hashed values\n";
        Map_hashed_by_key_iterator_t i = get<key>(m).begin();
        Map_hashed_by_key_iterator_t end = get<key>(m).end();
        for (;i != end; ++i) {
            cout << (*i).key_ << " " << (*i).data_ << endl;
        }
    }

    {
        cout << "Sequenced values\n";
        Map_sequenced_by_key_iterator_t i = get<key_seq>(m).begin();
        Map_sequenced_by_key_iterator_t end = get<key_seq>(m).end();
        for (;i != end; ++i) {
            cout << (*i).key_ << " " << (*i).data_ << endl;
        }
    }

    return 0;
}

关于c++ - 保留插入顺序的 C++ HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1899564/

相关文章:

html - 列表的奇数和偶数边界不起作用

html - 样式化水平导航

html - 列表中的 anchor 链接确实跨越整个列表

c++ - 变体类型和可变参数模板的转换和输出运算符

c++ - 在 C++ 中计算二项式系数模块素数 p

c++ - 测量忽略处理器速度的快速代码的性能/吞吐量?

c++ - 字符串和 unordered_map 运行缓慢

c++ - 如何在 C++ 中读取一行并用 '!!"分隔它?

c++ - 使用 C++11 中的 unordered_map 需要哪个 gcc 版本?

c++ - 如何用固定元素直接初始化unordered_map?