forked from pezy/CppPrimer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex11_3_4.cpp
51 lines (45 loc) · 1.27 KB
/
ex11_3_4.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
46
47
48
49
50
51
//! @Alan
//!
//! Exercise 11.3:
//! Write your own version of the word-counting program.
//!
//! Exercise 11.4:
//! Extend your program to ignore case and punctuation.
//! For example, “example.” “example,” and “Example” should
//! all increment the same counter.
//!
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <cctype>
//! Exercise 11.4
void word_count_pro(std::map<std::string, int>& m)
{
std::string word;
while (std::cin >> word) {
for (auto& ch : word) ch = tolower(ch);
//! According to the erase-remove idiom.
//! For more information about the erase-remove idiom, please refer to
//! http://en.wikipedia.org/wiki/Erase-remove_idiom
word.erase(std::remove_if(word.begin(), word.end(), ispunct),
word.end());
++m[word];
}
for (const auto& e : m) std::cout << e.first << " : " << e.second << "\n";
}
//! Exercise 11.3
void ex11_3()
{
std::map<std::string, std::size_t> word_count;
std::string word;
while (std::cin >> word) ++word_count[word];
for (const auto& elem : word_count)
std::cout << elem.first << " : " << elem.second << "\n";
}
int main()
{
std::map<std::string, int> m;
word_count_pro(m);
return 0;
}