(STL)std::unique函数的实现
来源:互联网 发布:python 3.7 编辑:程序博客网 时间:2024/05/16 16:05
源于《挑战程序设计竞赛》第164页程序中调用的函数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;测试程序如下:
#include <iostream>#include <vector>#include <algorithm>using namespace std;int main() { vector<int> ivec{1, 2, 2, 2, 3, 3, 2, 2, 1}; vector<int>::iterator last; last = unique(ivec.begin(), ivec.end()); for(vector<int>::iterator it = last; it != ivec.end(); ++it) { cout << *it << " "; } cout << endl; // 注意上述的输出, ivector 的size 并没有变。 //removes all duplicate elements from a //vector of integers. vector<int> ivec2{1, 2, 2, 2, 3, 3, 2, 2, 1}; sort(ivec2.begin(), ivec2.end()); auto last2 = unique(ivec2.begin(),ivec2.end()); for(const auto &i: ivec2) { cout << i << " "; } cout << endl; // 删除last2 到 ivec2.end() 的所以的元素 ivec2.erase(last2, ivec2.end()); // cout << ivec2.capacity() << endl; capacity 仍然为9, 只能用swap释放占用的内存了 for(const auto &i: ivec2) { cout << i << " "; } cout << endl; // 类似的见unique_copy return 0;}
运行结果如下:
0 0
- (STL)std::unique函数的实现
- vector容器 std::unique函数的实现
- unique函数(STL)
- unique函数的使用方法(STL库函数)
- STL库函数获取字符串包含的字符集(unique()函数)
- STL algorithm 之 unique 函数的用法
- STL中unique函数的用法
- stl vector unique函数
- STL-unique()函数
- STL-unique函数
- STL unique函数
- 【STL】unique函数
- STL:unique()函数
- STL unique()函数学习
- C++ STL unique函数
- 【C++ STL应用与实现】56: 使用std::unique删除重复元素
- std::unique (去重)
- C++ std::sort 函数的STL内部错误
- Crazyflie笔记一:概述开发范围、工具、特点介绍
- Spring RMI实现远程调用及源码
- 网站系统分布式架构
- Ubuntu安装和查看已安装程序包
- Android ListView 几个重要属性
- (STL)std::unique函数的实现
- 100万并发连接服务器笔记之1M并发连接目标达成
- Stock (zoj 2921 贪心经典)
- CentOs yum configuration
- java学习之文件字符流读取文件
- 2144
- Crazyflie笔记二:Crazyflie 1.0和2.0产品特点概述
- 6个值得推荐的Android开源框架简介
- nyoj-1162-数字