1

I am wondering if this is a standard that calling [] without assignment will initialize the value of this key-value pair to be 0, if value is of type int?

    // the way I did before, can I skip the if() checking?
    std::unordered_map<std::string, size_t>  word_map;
    for (const auto &w : { "this", "sentence", "is", "not", "a", "sentence",
                           "this", "sentence", "is", "a", "hoax"}) {
        if (!word_map.count(w)) {
            word_map[w] = 0;
        } else {
            ++word_map[w];
        }
    }

Can i do the following instead:

    std::unordered_map<std::string, size_t>  word_map;
    for (const auto &w : { "this", "sentence", "is", "not", "a", "sentence",
                           "this", "sentence", "is", "a", "hoax"}) {
        ++word_map[w];
    }

Thanks.

/*-------------
---------------
-------------*/

UPDATES:

I just checked out this page about en.cppreference.com/w/cpp/language/default_initialization it seems that if we reply on the default initialization int x; the value of x will be indeterminate. So I guess word_map[w] does not necessarily == 0 when first called?

John Tan
  • 147
  • 1
  • 9
  • See [`std::map::operator[]`](http://en.cppreference.com/w/cpp/container/map/operator_at). The same applies to `unordered_map`. The crucial detail is that the value `T()` is inserted. – juanchopanza Dec 18 '16 at 16:52
  • @juanchopanza Don't you mean... The value that is inserted? ;) I'll see myself out... – rwols Dec 18 '16 at 16:53
  • @rwols I don't follow :-P – juanchopanza Dec 18 '16 at 16:55
  • @juanchopanza you edited your comment! Now my comment doesn't make sense. Oh well. – rwols Dec 18 '16 at 16:58
  • @rwols Yeah, sorry. But thanks for pointing out it the original may have been confusing. – juanchopanza Dec 18 '16 at 16:59
  • I see, T() is inserted. Thanks!! – John Tan Dec 18 '16 at 17:09
  • I guess T() for double is 0.0 and for string is "". Or is there a T() for primitive types like int, double? – John Tan Dec 18 '16 at 18:01
  • I just checked out this page about http://en.cppreference.com/w/cpp/language/default_initialization it seems that if we reply on the default initialization int x; the value of x will be indeterminate. So I guess word_map[w] does not necessarily == 0 when first called? – John Tan Dec 18 '16 at 20:14
  • @JohnTan `T()` is called *value initialization*, not *default initialization*. That means zero-initialization got built-ins. Unfortunately the answers in the duplicate are all terrible and don't explain this properly. – juanchopanza Dec 18 '16 at 22:39

0 Answers0