unique和unique_copy函数的应用

本文介绍如何使用C++中的unique函数去除字符串中的相邻重复元素,并通过两个实例详细展示了其用法和效果。同时,阐述了unique_copy函数与unique的区别,以及如何在实际应用中灵活运用。

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

unique函数的功能是:去除相邻的重复元素(只保留一个)。函数参数:unique(first,last,compare);//first为容器的首迭代器,last为容器的末迭代器,compare为比较函数(可略写)。

注意:unique函数也并非是真正的删除了元素,一般要与erase成员函数 或resize成员函数互相配合使用。具体可参见博文:http://blog.sina.com.cn/s/blog_6d79d83a0100wh1f.html

看一个例题:给你一个字符串,删除字符串中相邻的重复元素,并打印字符串。

代码:

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
 
   stringstr;
   cin>>str;
   str.erase(unique(str.begin(),str.end()),str.end());
   //str.resize(unique(str.begin(),str.end())-str.begin());
   cout<<str<<endl;
    return0;
}


输入:
abbbccbba
输出:
abcba

unique_copy与unique的唯一区别在于:unique_copy会将进行删除相邻重复元素的结果保存在另外一个结果容器中。函数参数:unique_copy(first,last,result,compare);//first为容器的首迭代器,last为容器的末迭代器,result为保存结果的容器(原容器的内容不变),compare为比较函数(可略写)。
还是上一例题,这次使用unique_copy来实现。
代码:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
    stringfirst,second;
   cin>>first;
   second.resize(first.size());
   second.resize(unique_copy(first.begin(),first.end(),second.begin())-second.begin());
   cout<<second<<endl;
    return0;
}


输入:
abbbccbba
输出:
abcba
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值