std::hive<T,Allocator>::unique

来自cppreference.com
 
 
 
 
template< class BinaryPredicate = std::equal_to<T> >
size_type unique( BinaryPredicate binary_pred = BinaryPredicate() );
(C++26 起)

从容器移除所有相继 的重复元素。只留下相等元素组中的第一个元素。

更正式地说,对于非空的 hive,会擦除范围 [begin() + 1end()) 中所有满足 p(*i, *(i - 1)) 为 true 的迭代器 i 所引用的元素。

会使指向被擦除元素的引用、指针和迭代器失效。 如果 *this 中的最后一个元素被擦除,则也会使尾后迭代器失效。

如果对应的的比较器没有建立等价关系,那么行为未定义。

参数

p - 若元素应被当做相等则返回 ​true 的二元谓词

谓词函数的签名应等价于如下:

bool pred(const Type1 &a, const Type2 &b);

虽然签名不必有 const &,函数也不能修改传递给它的对象,而且必须接受(可为 const 的)类型 Type1Type2 的值,无关乎值类别(从而不允许 Type1&,也不允许 Type1 ,除非 Type1 的移动等价于复制(C++11 起))。
类型 Type1Type2 必须使得 hive<T,Allocator>::const_iterator 类型的对象能在解引用后隐式转换到这两个类型。 ​

类型要求
-
BinaryPredicate 必须满足二元谓词 (BinaryPredicate)

返回值

移除的元素数。

复杂度

empty()true 时不进行比较。

否则,给定 Nstd::distance(begin(), end()):  恰好应用 N-1 次谓词 p

示例

#include <iostream>
#include <hive>

std::ostream& operator<< (std::ostream& os, const std::hive<int>& container)
{
    for (int val : container)
        os << val << ' ';
    return os << '\n';
}

int main()
{
    std::hive<int> c{1, 2, 2, 3, 3, 2, 1, 1, 2};
    std::cout << "unique() 前:" << c;
    const auto count1 = c.unique();
    std::cout << "unique() 后:" << c
              << "移除了 " << count1 << " 个元素\n";
    
    c = {1, 2, 12, 23, 3, 2, 51, 1, 2, 2};
    std::cout << "\nunique(pred) 前:" << c;
    
    const auto count2 = c.unique([mod = 10](int x, int y)
    {
        return (x % mod) == (y % mod);
    });
    
    std::cout << "unique(pred) 后:" << c
              << "移除了 " << count2 << " 个元素\n";
}

输出:

unique() 前:1 2 2 3 3 2 1 1 2 
unique() 后:1 2 3 2 1 2 
移除了 3 个元素

unique(pred) 前:1 2 12 23 3 2 51 1 2 2 
unique(pred) 后:1 2 23 2 51 2 
移除了 4 个元素

参阅

移除范围中连续重复元素
(函数模板 & 算法函数对象)[编辑]
Morty Proxy This is a proxified and sanitized view of the page, visit original site.