motam79
motam79

Reputation: 3824

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

I would like to use C++ std::map to access the value associated to a given key in log(n) time. Since the keys of a std::map are sorted, technically, I can access the keys by the location in the sorted order. I know std::map does not have a random access iterator. Is there any "map like" data structure providing both access through the keys (by using the [] operator) and also providing the (read-only) random access though the location of the key in the sorted order. Here is a basic example:

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'

Upvotes: 1

Views: 4693

Answers (2)

You can use Boost.MultiIndex's 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");
}

Note, however, that nth is not O(1) but logarithmic, so ranked indices are not exactly random-access.

Postscript: Another alternative with true random access is Boost.Container's 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");
}

The downside here is that insertion takes linear rather than logarithmic time.

Upvotes: 1

Loki Astari
Loki Astari

Reputation: 264331

You could just iterate through them:

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'

Upvotes: 1

Related Questions