Namespaces
Variants

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

来自 zh.cppreference.net

 
 
 
 
void unique();
(1) (until C++20)
size_type unique();
(since C++20)
template< class BinaryPredicate >
void unique( BinaryPredicate p );
(2) (until C++20)
template< class BinaryPredicate >
size_type unique( BinaryPredicate p );
(since 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 必须使得 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 <list>

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

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

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

DR 适用范围 发布时的行为 正确行为
LWG 1207 C++98 未明确说明迭代器
和/或引用是否失效
仅使被移除元素的迭代器
和引用失效

参见

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