zangw
zangw

Reputation: 48536

How to initialize unordered_map directly with fixed element?

I want to initialize one unordered_map with fixed element 100. And the keys are from 0 to 100, all values of those keys are 0

using HashMap = unordered_map < int, int > ;

HashMap map;
for (int idx = 0; idx < 100; ++idx) {
    map[idx] = 0;
}

Question 1:

Is there any directly way to do that like the following codes in python?

d = {x: x % 2 == 0 for x in range(1, 11)}

Question 2:

With initialization codes above, I think all elements are sorted in ascending order, but the results are:

enter image description here

Why the first element is 8 and the second element is 64, all left elements are in ascending order?

Upvotes: 0

Views: 1251

Answers (2)

squid
squid

Reputation: 2625

  1. consider boost::irange

  2. the internal data structure for unordered map is hash table, which does not always hold key order during hashing.

Upvotes: 0

rici
rici

Reputation: 241931

  1. This is not quite so pretty as the Python expression, but it should do the trick.

    #include <algorithm>
    #include <iostream>
    #include <iterator>
    #include <unordered_map>
    
    int main() {
        std::unordered_map<int, bool> m;
        int i = -1;
        std::generate_n(std::inserter(m, m.begin()),
                        10,
                        [&i](){
                                 ++i;
                                 return std::make_pair(i, i % 2 == 0);
       });
       for (auto const &p: m)
           std::cout << '<' << p.first << ", " << p.second << ">\n";
       return 0;
    }
    

    Live on ideone.com

  2. There is a reason unordered maps are called unordered maps. Since they are implemented as hash maps, the keys are not in any predictable order. Using an std::unordered_map for a dense collection of integer keys is probably not the most efficient solution to any problem, particularly if you expect to be able to extract the keys in order.

Upvotes: 2

Related Questions