知识点:
1.使用空语句应加注释,让别人知道有意义。多余的空语句并非总是无害的。
2.快(block)即复合语句(compound statement), 块不以分号结束。
3.一般不省略case分支最后的break语句,如果没写,最好加注释说明。
4.最好不省略defualt标签。
5.不确定迭代多少次,用while循环比较合适
6.将一个整数读入vector用for实现:
vector <int> v;
for (int i ;cin>>i;)
v.push_back(i);
7, c++11新标准: 范围for语句(range for statement)
8. continue 语句 只能出现在 for,while, do while 循环的内部。switch要在迭代语句内部时才能在switch中用continue。
习题:
Exercise 5.14
Write a program to read strings from standard input looking for duplicated words. The program should find places in the input where one word is followed immediately by itself. Keep track of the largest number of times a single repetition occurs and which word is repeated. Print the maximum number of duplicates, or else print a message saying that no word was repeated. For example, if the input is
how now now now brown cow cow
the output should indicate that the word now occurred three times.
#include <iostream>
#include <string>
using std::cout; using std::cin; using std::endl; using std::string; using std::pair;
int main()
{
pair<string, int> max_duplicated;
int count = 0;
for (string str, prestr; cin >> str; prestr = str)
{
if (str == prestr) ++count;
else count = 0;
if (count > max_duplicated.second) max_duplicated = { prestr, count };
}
if (max_duplicated.first.empty()) cout << "There's no duplicated string." << endl;
else cout << "the word " << max_duplicated.first << " occurred " << max_duplicated.second + 1 << " times. " << endl;
return 0;
}