函数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