C++ primer 第五版 中文版 练习 10.11
题目:编写程序,使用stable_sort和isShorter将传递给你的elimDups版本的vector排序。打印vector的内容,验证你的程序的正确性。
答:
/*
编写程序,使用stable_sort和isShorter将传递给你的elimDups版本的vector排序。打印vector的内容,验证你的程序的正确性。
*/
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
bool isShorter(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}
void elimDups(vector<string> &words)
{
sort(words.begin(), words.end());
cout << "vector用sort重排后的元素内容为:";
for (auto a : words)
cout << a << " ";
cout << endl;
auto end_unique = unique(words.begin(), words.end());
cout << "vector用unique重排后的元素内容为:";
for (auto a : words)
cout << a << " ";
cout << endl;
words.erase(end_unique, words.end());
cout << "vector中删除重复元素后的内容为:";
for (auto a : words)
cout << a << " ";
cout << endl;
}
int main()
{
vector<string> svect = { "the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle" };
cout << "vector中原始元素内容为:";
for (auto a : svect)
cout << a << " ";
cout << endl;
elimDups(svect);
stable_sort(svect.begin(), svect.end(), isShorter);
cout << "按长度重新排序后的vector元素内容为:";
for (const auto &a : svect)
cout << a << " ";
cout << endl;
return 0;
}