题目要求:
假定已有一个vector,保存了多个故事的文本。我们希望简化这个vector,是的每个单词只出现一次,而不管单词在任意给定文档中到底出现了多少次。
可能这个题目要求读起来有点不好理解,见代码会很清晰:
#include "pch.h"
#include <iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
void elimdups(vector<string>& word);
int main()
{
//例 10.9
/*排序并且删除vector中重复的单词*/
string b;
vector<string> a;
while (cin >> b) { //当我们输入ctrl+z的时候才会停止,ctrl+z代表一个EOF字符,当cin碰到的时候,cin的状态就会改变
a.push_back(b);
}
elimdups(a);
}
void elimdups(vector<string>& word) {
sort(word.begin(), word.end()); //利用标准库中的sort函数模板来执行排序
for (auto b : word)
cout << b << " ";
cout << endl;
auto b=unique(word.begin(), word.end());
for (auto b : word)
cout << b << " "; //这里结果会有个疑问,为什么显示倒数第二个the但不显示最后一个turtle呢,
//被置为空了吗,那倒数第二个the为什么不被置为空呢
cout << endl;
cout << word.capacity() <<" "<< word.size() << endl;
word.erase(b, word.end());
for (auto b : word) {
cout << b << " ";
}
cout << endl;
cout << word.capacity() << " " << word.size() << endl;
}
输入:
fox jumps over quick red red slow the the turtle ctrl+z(cin是while循环中止的条件)
结果如下: