练习5.14
输入若干string对象,查找连续出现的单词和数目。
- 第一种方法
#include<iostream>
#include<vector>
#include<string>
int main()
{
using namespace std;
int count=1;
vector<string> v;
string str;
while (cin >> str)
{
v.push_back(str);
}
auto it = v.begin();
while(it!=v.end())
{
++it;
if (*(it-1) == *it) ++count;
else
{
cout << *(it -1)<< ":" << count << endl;
count = 1;
}
}
return 0;
}
- 第二种方法
#include<iostream>
#include<vector>
#include<string>
int main()
{
using namespace std;
string word, wordnext;
if (cin >> word)
{
int wordCnt = 1;
while (cin >> wordnext)
{
if (word == wordnext)
++wordCnt;
else
{
cout << word << " occurs" << wordCnt << " times" << endl;
word = wordnext;
wordCnt = 1;
}
}
cout << word << " occurs" << wordCnt << " times" << endl;
}
return 0;
}
以上代码需要注意迭代器的范围。
练习5.17
#include<iostream>
#include<vector>
int main()
{
using namespace std;
vector<int> v1 = { 0,1,1,3 }, v2 = { 0,1,1,2,3,5,8 };
auto it = v1.begin(), it2 = v2.begin();
for (; it != v1.end(); ++it, ++it2)
if (*it != *it2)
{
cout << "NO!" << endl;
return 0;
}
cout << "ture!!" << endl;
return 0;
}
练习5.20
#include<iostream>
#include<string>
int main()
{
using namespace std;
string str,temp;
cin >> str;
temp = str;
int count=0;
while (cin >> str)
{
if (temp == str)
{
++count;
cout << str << "连续重复" << endl;
break;
}
else temp = str;
}
if (count == 0) cout << "没有任何单词连续重复!" << endl;
return 0;
}
练习5.25(异常处理)
#include<iostream>
#include<stdexcept>
int main()
{
using namespace std;
int i, j;
while (cin >> i >> j)
{
try
{
if (j == 0)
throw runtime_error("j should not 0");//抛出异常,转到catch;
double k = i / j;
cout << k << endl;
}
catch(runtime_error err)//处理异常
{
cout << err.what() << "please try again?y or n!" << endl;
char ch;
cin >> ch;
if (isspace(ch) || ch == 'n') break;
}
}
return 0;
}