std::list<T,Allocator>::unique_C++中文网

(1)

void unique();

(C++20 前)

size_type unique();

(C++20 起)
(2)

template< class BinaryPredicate >
void unique( BinaryPredicate p );

(C++20 前)

template< class BinaryPredicate >
size_type unique( BinaryPredicate p );

(C++20 起)

从容器移除所有相继的重复元素。只留下相等元素组中的第一个元素。第一版本用 operator== 比较元素,第二版本用二元谓词 p 比较元素

参数

p - 若元素应被当做相等则返回 ​true 的二元谓词。

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

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

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

返回值

(无)

(C++20 前)

移除的元素数。

(C++20 起)

复杂度

与容器大小成线性

示例

#include <iostream>
#include <list>
 
int main()
{
  std::list<int> x = {1, 2, 2, 3, 3, 2, 1, 1, 2};
 
  std::cout << "contents before:";
  for (auto val : x)
    std::cout << ' ' << val;
  std::cout << '\n';
 
  x.unique();
  std::cout << "contents after unique():";
  for (auto val : x)
    std::cout << ' ' << val;
  std::cout << '\n';
 
  return 0;
}

输出:

contents before: 1 2 2 3 3 2 1 1 2
contents after unique(): 1 2 3 2 1 2

参阅