std::unique
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <algorithm> 中定义
|
||
template< class ForwardIt > ForwardIt unique( ForwardIt first, ForwardIt last ); |
(1) | |
template< class ForwardIt, class BinaryPredicate > ForwardIt unique( ForwardIt first, ForwardIt last, BinaryPredicate p ); |
(2) | |
删除所有连续重复的元素的范围
[first, last)
。卸下做是通过移动的范围内,在需要的时候在这样一种方式,要被擦除的元素将被覆盖。只有相等的元素的每个组中的第一个元素的在左边。元素之间的旧的和新的结束或范围保持不变。的第一个版本使用operator==
比较的元素,第二个版本使用给定的二元谓词p
.原文:
Removes all consecutive duplicate elements from the range
[first, last)
. Removing is done by shifting the range when needed in such a way that elements to be erased are overwritten. Only the first element in each group of equal elements is left. The elements between the old and the new end or the range are left intact. The first version uses operator==
to compare the elements, the second version uses the given binary predicate p
.目录 |
[编辑] 参数
first, last | - | 元素的范围内进行处理
|
p | - | binary predicate which returns true if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: bool pred(const Type1 &a, const Type2 &b); The signature does not need to have const &, but the function must not modify the objects passed to it. |
类型要求 | ||
-ForwardIt 必须满足 ForwardIterator 的要求。
| ||
-The type of dereferenced ForwardIt must meet the requirements of MoveAssignable .
|
[编辑] 返回值
前向迭代器新的范围
原文:
Forward iterator to the new end of the range
[编辑] 可能的实现
版本一 |
---|
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; } |
版本二 |
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; } |
[编辑] 示例
下面的代码将删除所有连续相等的元素的向量整数.
原文:
The following code removes all consecutive equivalent elements from a vector of integers.
#include <iostream> #include <algorithm> #include <vector> int main() { std::vector<int> v{1, 2, 2, 2, 3, 3, 2, 2, 1}; std::vector<int>::iterator last; last = std::unique(v.begin(), v.end()); // 1 2 3 2 1 3 2 2 1 // ^ for (std::vector<int>::iterator it = v.begin(); it != last; ++it) { std::cout << *it << " "; } std::cout << "\n"; }
输出:
1 2 3 2 1
[编辑] 复杂度
线性
first
和last
之间的距离原文:
linear in the distance between
first
and last
[编辑] 另请参阅
查找彼此相邻的两个相同(或其它的关系)的元素 (函数模板) | |
删除区间内连续重复的元素并复制 (函数模板) |