C++primer Plus10.2.3排列容器中的元素并且删除重复值的算法
这里用到sort和unique算法,因为算法不能执行容器的操作(删除重复元素),所以还需要使用vector的erase成员函数
调用所需的头文件
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
具体操作封装在elimDups函数中,其中auto end_unique=unique(x.begin(),x.end());`返回一个指向不重复元素末尾的迭代器。
void elimDups(vector<string> &x)
{
sort(x.begin(),x.end())
auto end_unique=unique(x.begin(),x.end());
x.erase(end_unique,x.end());
}
主函数:
using namespace std;
void elimDups(vector<string> &x);
int main() {
vector<string> words;
words.push_back("the");
words.push_back("quick");
words.push_back("red");
words.push_back("fox");
words.push_back("jumps");
words.push_back("over");
words.push_back("the");
words.push_back("slow");
words.push_back("red");
words.push_back("turtle");
elimDups(words);
for(vector<string>::iterator iter = words.begin(); iter != words.end();++iter)
{
cout<<*iter<<" ";
}
cout<<endl;
}
函数输出:
fox jumps over quick red slow the turtle
Process finished with exit code 0