std::unique()函数(转)

unique是 c++标准模板库STL中十分实用的函数之一,使用此函数需要

	#include <algorithm>

一,

	该函数的作用是“去除”容器或者数组中相邻元素的重复出现的元素,注意 
		 (1) 这里的去除并非真正意义的erase,而是将重复的元素放到容器的末尾,返回值是去重之后的尾地址。 
		 (2) unique针对的是相邻元素,所以对于顺序顺序错乱的数组成员,或者容器成员,需要先进行排序,可以调用std::sort()函数

使用示例如下:

#include <iostream>
#include <algorithm>

int main(void)
{
    int a[8] = {2, 2, 2, 4, 4, 6, 7, 8};
    int c;

    //std::sort(a, a + 8);  //对于无序的数组需要先排序

    c = (std::unique(a, a + 8) - a );

    std::cout<< "c = " << c << std::endl;

    //打印去重后的数组成员
    for (int i = 0; i < c; i++)
        std::cout<< "a = [" << i << "] = " << a[i] << std::endl;

    return 0;
}

在这里插入图片描述

返回值c等于5,而a数组的前5项为2、4、6、7、8。
对于容器的操作类似:

std::vector<int> ModuleArr;
//排序
std::sort(ModuleArr.begin(), ModuleArr.end());
//去重
ModuleArr.erase(unique(ModuleArr.begin(), ModuleArr.end()), ModuleArr.end());

原文整理链接

版本1的可能的实现方式:

template<class ForwardIt>  
ForwardIt unique(ForwardIt first, ForwardIt last)  
{  
    if (first == last)  
        return last;  
   
    ForwardIt result = first;  
    while (++first != last) {  
        if (!(*result == *first)) {  
            *(++result) = *first;  
        }  
    }  
    return ++result;  
}	
	
	所一, 最终返回的一个迭代器指向任务结束的位置past the end.

版本二的实现方式:

template<class ForwardIt, class BinaryPredicate>  
ForwardIt unique(ForwardIt first, ForwardIt last,   
                       BinaryPredicate p)  
{  
    if (first == last)  
        return last;  
   
    ForwardIt result = first;  
    while (++first != last) {  
        if (!p(*result, *first)) {  
            *(++result) = *first;  
        }  
    }  
    return ++result;  
原文地址:https://www.cnblogs.com/spruce/p/13347577.html