Namespaces
Variants

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

来自 zh.cppreference.net

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

从容器中移除所有连续的重复元素。每组相等元素中只保留第一个元素。

更正式地说,对于非空的hive,删除所有由迭代器i在[begin() + 1, end())中所引用的元素,这些元素满足p(*i, *(i - 1))为真。

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

如果相应的比较器不建立等价关系,则行为未定义。

参数

p - 二元谓词,如果元素应被视为相等则返回true。

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

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

虽然签名不需要有const &,但函数不能修改传递给它的对象,并且必须能够接受类型(可能为const)为Type1和Type2的所有值,无论值类别(因此,不允许Type1 &,也不允许Type1,除非对于Type1移动等价于复制(C++11起))。
类型Type1和Type2必须使得类型为hive<T,Allocator>::const_iterator的对象可以被解引用并隐式转换为它们两者。 ​

类型要求
-
BinaryPredicate必须满足BinaryPredicate的要求。

返回值

被删除的元素数量。

复杂度

如果empty()为true,则不进行任何比较。

否则,给定N作为std::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 << "Before unique(): " << c;
    const auto count1 = c.unique();
    std::cout << "After unique():  " << c
              << count1 << " elements were removed\n";
    
    c = {1, 2, 12, 23, 3, 2, 51, 1, 2, 2};
    std::cout << "\nBefore unique(pred): " << c;
    
    const auto count2 = c.unique([mod = 10](int x, int y)
    {
        return (x % mod) == (y % mod);
    });
    
    std::cout << "After unique(pred):  " << c
              << count2 << " elements were removed\n";
}

输出:

Before unique(): 1 2 2 3 3 2 1 1 2
After unique():  1 2 3 2 1 2
3 elements were removed

Before unique(pred): 1 2 12 23 3 2 51 1 2 2
After unique(pred):  1 2 23 2 51 2
4 elements were removed

参见

移除范围内连续的重复元素
(函数模板 & 算法函数对象)
(C++20)