forked from Mooophy/Cpp-Primer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex11_21.cpp
45 lines (40 loc) · 1.21 KB
/
ex11_21.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//! @Alan
//!
//! Exercise 11.21:
//! Assuming word_count is a map from string to size_t and word is a string,
//! explain the following loop:
//! while (cin >> word)
//! ++word_count.insert({word, 0}).first->second;
//!
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <set>
#include <vector>
#include <iterator>
int main()
{
std::map<std::string, size_t> word_count;
std::string word;
while(std::cin >> word)
{
/*
//! insert the pair {word,0} into the map and get the iterator.
auto it = word_count.insert({word,0});
//! check if the pair is inserted
//! if not, increment the value of the key-value of the pair
if(!it.second)
++it.first->second;
*/
++word_count.insert({word, 0}).first->second;
//! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//! similiar to the codes above it, but more accurate and efficient
//! the increment operator "++" is excuted as ++ (word_count.insert({word, 0}).first->second)
//! print the content of the map.
for(auto e : word_count)
std::cout << e.first << " "
<< e.second << "\n";
}
return 0;
}