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;  

 

转载于:https://www.cnblogs.com/wangshaowei/p/9622350.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值