我想使用C ++ std::map以log(n)时间访问与给定键关联的值。由于std::map的键是排序的,因此从技术上讲,我可以按排序顺序按位置访问键。
我知道std :: map没有随机访问迭代器。是否有任何“像地图一样”的数据结构既提供通过键的访问(通过使用[]运算符),又通过键的位置按排序顺序提供(只读)随机访问。这是一个基本示例:

my_fancy_map['a'] = 'value_for_a'
my_fancy_map['b'] = 'value_for_b'

assert my_fancy_map.get_key_at_location(0) == 'a'
assert my_fancy_map.get_key_at_location(1) == 'b'
assert my_fancy_map.get_value_at_location(1) == 'value_for_b'
assert my_fancy_map['a'] == 'value_for_a'

最佳答案

您可以使用Boost.MultiIndex的ranked indices

Live On Coliru

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ranked_index.hpp>
#include <boost/multi_index/member.hpp>

using namespace boost::multi_index;

template<typename K,typename T>
using ranked_map=multi_index_container<
  std::pair<K,T>,
  indexed_by<
    ranked_unique<member<std::pair<K,T>,K,&std::pair<K,T>::first>>
  >
>;

#include <cassert>
#include <string>

int main()
{
  ranked_map<std::string,std::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),而是对数,因此排名索引并非完全是随机访问的。

后记:真正的随机访问的另一种选择是Boost.Container的flat associative containers

Live On Coliru

#include <boost/container/flat_map.hpp>
#include <cassert>
#include <string>

int main()
{
  boost::container::flat_map<std::string,std::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");
}


这里的缺点是插入需要线性而不是对数时间。

08-06 01:12
查看更多