欢迎访问我的个人网站==》 jiashubing.cn

unique() 去重函数

unique()函数是一个去重函数,STL中unique的函数 unique的功能是去除相邻的重复元素(只保留一个),还有一个容易忽视的特性是它并不真正把重复的元素删除。他是c++中的函数,所以头文件要加#include<iostream>,#include<algoritjm>,具体用法如下:

    int num[100];

   unique(num,mun+n)返回的是num去重后的尾地址,之所以说比不真正把重复的元素删除,其实是,该函数把重复的元素移到后面去了,然后依然保存到了原数组中,然后返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。

 


 

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

注意:unique函数也并非是真正的删除了元素,一般要与erase成员函数 或 resize成员函数互相配合使用。

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

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

输入:

  abbbccbba

输出:

   abcba

若只想知道输出字符串的长度

 

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

  

posted @ 2013-09-20 11:36  贾树丙  阅读(1979)  评论(0编辑  收藏  举报