C++ map<K,T> Initialization
c++, dictionary, stl, variable-assignment
Solution
You have such a map:
sts::map<std::string, int> m;
The access operator `[key]` gives you a reference to the element stored with that key, or inserts one if it doesn't exist. So for an empty map, this
m["hello"];
inserts an entry in the map, with key "Hello" and value 0. It also returns a reference to the value. So you can increment it directly:
m["Bye"]++;
would insert a value 0 under key "Bye" and increment it by one, or increment an existing value by 1.
As for the stuff happening inside the `[]` operator,
*begin++
is a means to incrementing the `istream_iterator` and dereferencing the value before the increment:
begin++;
increments `begin` and returns the value before the increment
*someIterator
dereferences the iterator.
Problem
I'm reading "Ivor Horton's Beginning Programming Visual C++ 2010", and I'm at Chapter 10-The Standard Template Library. My problem is with the map container `map<Person, string> mapname`. The book showed me a lot of ways of adding elements to it, such as with the `pair<K, T>` and using the `make_pair()` function later, and `mapname.insert(pair)`. But suddenly he introduced an element adding technique used in the following code: ``` int main() { std::map<string, int> words cout << "Enter some text and press Enter followed by Ctrl+Z then Enter to end:" << endl << endl; std::istream_iterator<string> begin(cin); std::istream_iterator<string> end; while(being != end) // iterate over words in the stream //PROBLEM WITH THIS LINE: words[*begin++]++; // Increment and store a word count //there are still more but irrelevant to this question) } ``` The indicated line is my problem. I understand that `words` is the map, but I've never seen such initialization. And what's going on in that thing with its increment. I believe Ivor Horton failed to elaborate this further, or at least he should've given introductions big enough not to suprise noobs like me.