C++中unique(),unique_copy()和erase()

函数1 unique()的用法,
unique()两个参数,第一个是首地址,第二个是末地址(stl区间默认为左闭右开),
他的原理是通过相邻比较(这就要求在处理之前用sort排序)删除重复的元素,但是不会真正的删除,而是会放到尾地址后面(为了这个套路,不会返回真正的尾地址,尾地址前面都是不重复的元素),就是酱紫;可以用来比较数字,不只是字符串。
2 而unique-copy的方法作用是将得到的不重复的字符串给一个新的对象,具体参数方法见代码、m.begin()写两次我也很郁闷,就这样记住吧。。
3 erase有三种方法;
erase函数的原型如下:
(1)string& erase ( size_t pos = 0, size_t n = npos );
(2)iterator erase ( iterator position );
(3)iterator erase ( iterator first, iterator last );
也就是说有三种用法:
(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position);删除position处的一个字符(position是个string类型的迭代器)
(3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)

string str = "uniquelike";  
vector<char> vecch(str.begin(), str.end()); //根据迭代器的起始位置和终止位置来定初始化一个容器  
vector<char>::iterator it = vecch.begin();  
for (; it != vecch.end(); ++it)  
{  
    cout<<*it;  
}  
cout<<endl;  迭代器输出方式。  
#include <bits/stdc++.h>
using namespace std;


int main()
{    string a="iiiamamhahaha";
    string m;
    m.resize(a.size());
     //int len=a.length();
     //sort(a,a+len);
     sort(a.begin(),a.end());
     int x=unique(a,a+len)-a;
     //此函数将数组排序,然后将相同的字放在后面,返回的不包含这些值的地址;
     a.erase(unique(a.begin(),a.end()),a.end());
     /*将那些没删的真正给他删除了,
     第一个返回的位置要删除位置的开始,后面是end。*/
     m.resize(unique_copy(a.begin(),a.end(),m.begin())-m.begin());
   cout<<m<<endl;



    return 0;
}
string str = "zhaohaoyang";  
string dststr;  
dststr.resize(str.size());  
sort(str.begin(), str.end());  
dststr.resize(unique_copy(str.begin(), str.end(), dststr.begin()) - dststr.begin());  
cout<<dststr<<endl;   //输出:aghnoyz  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值