你可以使用Boost.MultiIndex的ranked indices:
Live On Coliru
#include
#include
#include
using namespace boost::multi_index;
template
using ranked_map=multi_index_container<
std::pair,
indexed_by<
ranked_unique,K,&std::pair::first>>
>
>;
#include
#include
int main()
{
ranked_map<:string> m;
m.emplace("a","value for a");
m.emplace("b","value for b");
assert(m.nth(0)->first=="a");
assert(m.nth(1)->first=="b");
assert(m.nth(1)->second=="value for b");
assert(m.find("a")->second=="value for a");
}
但请注意, nth 不是O(1)而是对数,因此排名索引不是完全随机访问 .
Postscript: 具有真正随机访问的另一种选择是Boost.Container的flat associative containers:
Live On Coliru
#include
#include
#include
int main()
{
boost::container::flat_map<:string> m;
m["a"]="value for a";
m["b"]="value for b";
assert(m.nth(0)->first=="a");
assert(m.nth(1)->first=="b");
assert(m.nth(1)->second=="value for b");
assert(m["a"]=="value for a");
}
这里的缺点是插入需要线性而不是对数时间 .