Exercise 10.9WriteProgramCount and output the number of times the read words appear
Method 1:
# Include <iostream>
# Include <vector>
# Include <map>
# Include <string>
Using namespace STD;
Int main ()
{
Map <string, int> word_count;
String word;
While (CIN> word)
{
++ Word_count [word];
}
For (Map <string, int >:: iterator map_it = word_count.begin (); map_it! = Word_count.end (); ++ map_it)
Cout <map_it-> first <"" <map_it-> second <Endl;
Cout <Endl;
Return 0;
}
Method 2:
# Include <iostream>
# Include <vector>
# Include <map>
# Include <string>
Using namespace STD;
Int main ()
{
Map <string, int> word_count;
String word;
While (CIN> word)
{
Pair <Map <string, int >:: iterator, bool> P = word_count.insert (make_pair (word, 1 ));
/*
P is a pair variable. The first element is the map <string, int> container iterator, and the second element is the bool type. The insert operation adds an object with the string word key and the int 1 value to the word_count container. The insert operation returns pair to P, the first element iterator of P points to string word, And when word does not exist in word_count, the second element of P is true, and the existence is false. If (P. Second = false) is used to determine that if a word exists in word_count, the operation in the IF statement is executed.
*/
If (P. Second = false)
{
+ P. First-> second;
/*
It can be understood:
++ (* (P. First). Second ); |
P. first is the iterator pointing to the string word object in the word_count container. By referencing the iterator, The word_count container's key is the string word object. The object type is Map <string, int>:: valut_type. Value_type is of the pair type. Run. Second on the object to obtain that the second element type is int. In this program, it is the number of word occurrences. Finally, perform the auto-increment operation on the second element of the int type.
*/
}
}
For (Map <string, int >:: iterator map_it = word_count.begin (); map_it! = Word_count.end (); ++ map_it)
Cout <map_it-> first <"" <map_it-> second <Endl;
Cout <Endl;
Return 0;
}