Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

forward_list::unique

公众成员函数  <forward_list>
(1)
void unique();
(2)
template <class BinaryPredicate>
  void unique (BinaryPredicate binary_pred);

删除重复的值

不带参数(1)的版本从容器中连续的相等元素组中删除除第一个元素外的所有元素。

注意,只有当一个元素与它前面的元素比较时,它才会从forward_list容器中移除。 因此,这个函数对于已排序的容器特别有用。

第二个版本(2)采用一个确定元素“唯一性”的特定比较函数作为参数。
事实上,任何行为都可以实现(不仅相等的比较),但请注意,函数将对所有元素(i 是一个元素的迭代器,从第二个开始) 调用binary_pred(*i,*(i-1))并且如果谓词返回true,从forward_list删除i。

移除的元素被销毁。

☲  参数


binary_pred
二元断言,取两个与forward_list中包含的相同类型的值, 返回true以删除作为容器第一个参数传递的元素,否则返回false。

☉  返回值



none

☣  示例



// forward_list::unique
#include <iostream>
#include <cmath>
#include <forward_list>

// a binary predicate implemented as a function:
bool same_integral_part (double first, double second)
{ return ( int(first)==int(second) ); }

// a binary predicate implemented as a class:
class is_near_class
{
public:
  bool operator() (double first, double second)
  { return (fabs(first-second)<5.0); }
} is_near_object;

int main ()
{

  std::forward_list<double> mylist = { 15.2, 73.0, 3.14, 15.85, 69.5,
                                       73.0, 3.99, 15.2, 69.2,  18.5 };

  mylist.sort();                       //   3.14,  3.99, 15.2, 15.2, 15.85
                                       //  18.5,  69.2,  69.5, 73.0, 73.0

  mylist.unique();                     //   3.14,  3.99, 15.2, 15.85
                                       //  18.5,  69.2,  69.5, 73.0

  mylist.unique (same_integral_part);  //  3.14, 15.2, 18.5,  69.2, 73.0

  mylist.unique (is_near_object);      //  3.14, 15.2, 69.2

  std::cout << "mylist contains:";
  for (double& x: mylist) std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}


输出:
mylist contains: 3.14 15.2 69.2

✥ 复杂度



线性容器大小减1。.

☣ 迭代器的有效性



指向被函数删除的元素的迭代器、指针和引用将失效。
所有其他迭代器、指针和引用都保持其有效性。

⇄ 数据竞争


容器被修改.
并发访问或修改其他的元素是安全的,但遍历容器是不安全的。

☂ 异常安全性



如果保证binary_pred或元素的比较不会抛出异常,则函数永远不会抛出异常(no-throw保证)。
否则,如果抛出异常,容器将保持有效状态(基本保证)。

🍄  另请参阅



forward_list::remove 删除具有特定值的元素(公共成员函数)
forward_list::erase_after 删除元素 (公共成员函数)
forward_list::remove_if 移除满足条件的元素 (公共成员函数)
forward_list::pop_front 删除第一个元素 (公共成员函数)
forward_list::sort 对容器中的元素进行排序 (公共成员函数)

联系我们 免责声明 关于CandCplus 网站地图