삽입 순서를 보존하는 C ++ 해시 맵 [복제
-
19-09-2019 - |
문제
이 질문은 이미 여기에 답이 있습니다.
- 삽입 순서를 추적하는 STD ::지도? 14 답변
다음 코드가 있습니다.
#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;
}
다른 팁
맵과 벡터의 조합을 사용하여 순서 맵을 만들 수 있습니다.
- 벡터는 키와 값 쌍을 보유 할 수 있습니다.
- 벡터 반복자는 순서대로 반복자로 사용할 수 있습니다.
- 맵을 사용할 수 있습니다. 요소에 더 빨리 액세스 할 수 있습니다.
제휴하지 않습니다 StackOverflow