std::unique实现

std::unique适用于将排过序的数据结构重复的部分全部放在结尾

但用的时候发现会将原先容器中的内容改掉,看了源码发现这个函数会将不重复的数据结构直接覆盖到前一个重复的位置上,下面看源码

该函数std::unique位于头文件<algorithm>声明1如下:

template< class ForwardIt >  
ForwardIt unique( ForwardIt first, ForwardIt last ); 

声明2如下:

template< class ForwardIt, class BinaryPredicate >  
ForwardIt unique( ForwardIt first, ForwardIt last, BinaryPredicate p );  

该函数的作用为: 删除[first, last)之间所有连续重复的元素, 只保留一个。 注意, 是连续重复。 要删除所有重复的元素, 只需要排序之后, 然后调用这个函数即可实现。 第一个版本通过==判断是否重复, 第二个版本通过二元谓词p判断是否重复。 

 

二元谓词p, 就是binary predicate which returns ​true if the elements should be treated as equal. 

版本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;  

 

posted @ 2018-09-10 19:58  大老虎打老虎  阅读(2105)  评论(0编辑  收藏  举报