命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | 容器‎ | forward_list
 
 
 
 
(1)
void unique();
(C++11 起)
(C++20 前)
size_type unique();
(C++20 起)
(2)
template< class BinaryPredicate >
void unique( BinaryPredicate p );
(C++11 起)
(C++20 前)
template< class BinaryPredicate >
size_type unique( BinaryPredicate p );
(C++20 起)

从容器中移除所有连续的重复元素。每组相等元素中只保留第一个元素。仅使指向被移除元素的迭代器和引用失效。

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

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

目录

[edit] 参数

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

谓词函数的签名应等效于以下内容:

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

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

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

[edit] 返回值

(无)

(C++20 前)

被移除元素的数量。

(C++20 起)

[edit] 复杂度

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

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

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

[edit] 注解

特性测试 标准 特性
__cpp_lib_list_remove_return_type 201806L (C++20) 更改返回类型

[edit] 示例

#include <iostream>
#include <forward_list>
 
std::ostream& operator<< (std::ostream& os, std::forward_list<int> const& 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

[edit] 参阅

移除一个范围中的连续重复元素
(函数模板) [编辑]