【C++】删除顺序容器(如:vector)中的重复字符串

本文介绍了一个使用 C++ 实现字符串数组去重的例子。通过 `unique()` 和 `erase()` 函数组合使用,有效地移除数组中的重复元素,并保持原有的顺序不变。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main(int argc, const char * argv[])   
{     
    stringstream sentence("the quick red fox jumps over the slow red turtle");
    string word;
    vector<string> words;
    while (sentence >> word)
    {
        words.push_back(word);
    }
    sort(words.begin(), words.end());
    vector<string>::iterator unque_iter  = unique(words.begin(), words.end());
    words.erase(unque_iter, words.end());
    return 0;  
}


说明: unique()函数返回的是指向没有重复内容的下一个位置。而且其并不是删除其中的重复元素,只是将其移到容器的末尾,所以还需要自己待用erase()来彻底删除.

C++,unique(),erase,重复

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值