C++ primer 第五版 中文版 练习 11.8
题目:编写一个程序,在一个vector而不是一个set中保存不重复的单词。使用set的优点是什么?
答:用set的优点是简单,直接赋值即可。
#include <iostream>
#include <vector>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
vector<string> words{ "C++", "my", "C++", "c", "is", "world", "c", "like" };
vector<string> svect;
//转换为list<string> 去重复。
list<string> slist(words.cbegin(), words.cend());
slist.sort();
slist.unique();
// 直接用泛型算法去重复。
// sort(words.begin(), words.end());
// auto iter = unique(words.begin(), words.end());
// words.erase(iter, words.end());
for (const auto &w : slist)
svect.push_back(w);
for (const auto &v : svect)
cout << v << " ";
cout << endl;
return 0;
}