Raghav Navada
Raghav Navada

Reputation: 317

Initialize c++14 unordered_map with k buckets with key-value pair of zero

I am trying to create an unordered_map with minimum number of initial buckets(k), with all key-value pairs initialized to zero. Later, it should go inside the for loop and print values.

int someFunction(int k){
  unordered_map<int, int> majority(k, {0,0});
}

for(auto m : majority){
  cout << m.first << " " <<  m.second << " \n";
}

I get the following compilation(c++ 14) error:

no matching function for call to ‘std::unordered_map<int, int>::unordered_map(int&, <brace-enclosed initializer list>)

Is there a way I can achieve this?

Upvotes: 1

Views: 570

Answers (2)

Stephan Dollberg
Stephan Dollberg

Reputation: 34528

std::unordered_map only supports unique keys so that constructor doesn't exist.

If you want the same key multiple times you can use a std::unordered_multimap. See the reference for the available constructors.

#include <iostream>
#include <unordered_map>

int main() {

    std::unordered_multimap<int, int> map;
    const int k = 5;

    for (int i = 0; i < k; ++i)
    {
        map.emplace(0, 0);
    }

    for (auto& kv: map)
    {
        std::cout << kv.first << " " << kv.second << std::endl;
    }

}

Upvotes: 1

Alex
Alex

Reputation: 1021

unordered_map represents hash data structure. By hash definition every key must be unique. So you can`t initialize majority with several zero int keys. Instead you can use reserve function :

void reserve ( size_type n );

Request a capacity change

Sets the number of buckets in the container (bucket_count) to the most appropriate to contain at least n elements.

If n is greater than the current bucket_count multiplied by the max_load_factor, the container's bucket_count is increased and a rehash is forced.

If n is lower than that, the function may have no effect.

Upvotes: 1

Related Questions