命名空间
变体
操作

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 比较元素。

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

目录

[编辑] 参数

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

谓词函数的签名应等效于以下形式

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

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

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

[编辑] 返回值

(无)

(直至 C++20)

移除的元素数量。

(始于 C++20)

[编辑] 复杂度

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

否则,给定 Nstd::distance(begin(), end())

1) 精确地使用 operator== 进行 N-1 次比较。
2) 精确地应用谓词 p N-1 次。

[编辑] 注释

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

[编辑] 示例

#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

[编辑] 参见

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