Namespaces
Variants

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

来自 zh.cppreference.net

 
 
 
 
void unique();
(1) (自C++11起)
(直至C++20)
size_type unique();
(自C++20起)
template< class BinaryPredicate >
void unique( BinaryPredicate p );
(2) (自C++11起)
(直至C++20)
template< class BinaryPredicate >
size_type unique( BinaryPredicate p );
(自C++20起)

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

仅使指向被移除元素的迭代器和引用失效。

1) 使用 operator== 比较元素。
2) 使用 p 比较元素。

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

参数

p - 二元谓词,若应视元素为相等则返回 ​ true 。

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

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

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

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

返回值

(无)

(C++20 前)

被移除的元素数量。

(C++20 起)

复杂度

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

否则,给定 N 为 std:: distance ( begin ( ) , end ( ) ) :

1) 恰好需要 N-1 次使用 operator == 的比较。
2) 恰好需要 N-1 次谓词 p 的应用。

注释

功能测试 宏 值 标准 功能特性
__cpp_lib_list_remove_return_type 201806L (C++20) 修改返回类型

示例

#include <iostream>
#include <forward_list>

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

int main()
{
    std::forward_list<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

参阅

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