簡體   English   中英

C ++ std :: map如何通過索引位置訪問鍵

[英]C++ std::map how to access keys by index location

我想使用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的排名索引

生活在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的扁平關聯容器

生活在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");
}

這里的缺點是插入需要線性而不是對數時間。

您可以遍歷它們:

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

auto location = std::begin(my_fancy_map);
assert location.first == 'a'
++location;
assert location.first == 'b'
assert location.second == 'value_for_b'
assert my_fancy_map['a'] == 'value_for_a'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM