C++primer Plus10.2.3排列容器中的元素并且删除重复值的算法

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值