1

I am thinking about the problem of counting elements of specific values of map and how to achieve O(log(N)) complexity in C++. It is would be only possible when it is sorted by the values I guess, but then it would not be sorted by keys and the get from map would be then O(N).

In the first version I use std::count_if. Here is my code:

std::count_if( std::begin(_map), std::end(_map),
    [&val]( const std::pair<const std::string,  std::string> &p )
    {
        return p.second == val;
    } );

It has complexity the O(N). Do you know any other containers which would be useful for this problem? I was thinking about tree map but there might be a similar problem of sorting by keys.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Przemekeke
  • 81
  • 10

4 Answers4

2

Boost's bimap allows lookup by either key or value.

auto range = map.right.equal_range(val);
std::distance(range.first, range.second);
Caleth
  • 52,200
  • 2
  • 44
  • 75
1

You could maintain two maps so items would be indexed by by both key and value. You would need a multimap to allow for duplicate values.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • I was considering this as well but it doubling the memory usage and it would be problem with big maps. I am thinking about this solution as a trade off – Przemekeke Apr 30 '21 at 08:22
1

Depending one your other typical uses of the container you can consider to use a std::vector<std::pair<key_t,mapped_t>> instead of the map. You have to do the sorting yourself, but you can sort for keys or values, and then do a binary search.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

I've got an idea that it can be achieved by creating a hash_map hash function which increments bucket value by one if the value from map equals the bucket key. Then, it is only a matter of reading bucket values.

Przemekeke
  • 81
  • 10
  • Add this to the description of the problem. – Rishabh Deep Singh Sep 14 '21 at 16:33
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask). – Community Sep 14 '21 at 16:33