练习 11.8:编写一个程序,在一个vector而不是一个set中保存不重复的单词。使用set的优点是什么?
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string test_str = "one two three four two five one six";
vector<string> vec;
string word;
istringstream iss(test_str);
while(iss >> word)
{
if(find(vec.cbegin(), vec.cend(), word) == vec.cend())
vec.push_back(word);
}
//Print vector all elements
for(auto e : vec)
cout << e << " ";
return 0;
}
执行结果:
由于不能存入重复的单词,因此在将word录入vector之前,先通过find算法函数在vector中查找一遍,在没有搜寻到word的情况下,才会将word存入vector。
如果使用set的话,它会保证关键字的惟一性,由set自己来处理关键字重复问题,省去我们自己来处理了。