前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++如何简单快速去除容器中的重复元素

C++如何简单快速去除容器中的重复元素

作者头像
六月丶
发布2022-12-26 17:19:16
2.2K0
发布2022-12-26 17:19:16
举报
文章被收录于专栏:六月-游戏开发六月-游戏开发

假设在vector strs中有一些单词(全小写),包含重复出现的元素,现在需要统计其中出现过哪些单词,那么有什么简单高效的去除方法呢? 这里推荐两种方法: 一种是用algorithm的函数 先用sort排序,让重复元素相邻,再用unique把重复元素移至容器末尾,最后用erase把末尾重复元素删除。 源码如下:

include

代码语言:javascript
复制
#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main(){
    string str[] = {"word","yellow","at","number","yellow","at","student","number"};
    vector<string> strs(str,str+8);
    //去重复
    sort(strs.begin(),strs.end());  
    auto end_unique = unique(strs.begin(),strs.end());  
    strs.erase(end_unique,strs.end());

    return 0;
}

如果在其中插入输出语句,结果为: 初始化后: word yellow at number yellow at student number sort后:at at number number student word yellow yellow unique后:at number student word yellow number at yellow erase后:at number student word yellow

另一种是用set容器转存 因为set容器默认不会存入重复元素,所以直接用strs初始化set容器即可达到去重复的目的 源码如下:

代码语言:javascript
复制
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<set>

using namespace std;

int main(){
    string str[] = {"word","yellow","at","number","student","at","word","number"};
    vector<string> strs(str,str+8);

    set<string> se(strs.begin(),strs.end());

    return 0;
}

如果在末尾插入输出语句,结果为: strs:word yellow at number yellow at student number se:at number student word yellow 相比于上面的方法,用set转存的优点是一条语句就能完成去重复,缺点是原容器strs不会发生改变,只是把去重复的结果放进了se中。 注意:这两种方法虽然简单,但都可能会改变strs中元素的相对顺序,如果不想改变相对顺序,可以用下面这个方法。 把strs中元素依次存入set容器中,如果某个元素存入失败,就从strs中把这个元素删除。即可达到不改变顺序去除strs中的重复元素。 源码如下:

代码语言:javascript
复制
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<set>

using namespace std;

int main(){
    string str[] = {"word","yellow","at","number","yellow","at","student","number"};
    vector<string> strs(str,str+8);

    set<string> se;
    for(vector<string>::iterator it = strs.begin();it!=strs.end();){
        pair<set<string>::iterator,bool> ret = se.insert(*it);
        if(ret.second==false){strs.erase(it);continue;}
        it++;
    }

    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019 年 09 月,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • include
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档