1. 程式人生 > 實用技巧 >std::unique()函式(轉)

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;