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

std::

list::unique

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

删除重复的值

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

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

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

移除的元素被销毁.

☲  参数


binary_pred
二元断言,检验两个容器中包含的值, 如果返回true则删除作为容器第一个参数传递的元素,否则返回false。

这应该是一个函数指针或函数对象。

☉  返回值



none

☣  示例



// list::unique
#include <iostream>
#include <cmath>
#include <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:
struct is_near {
  bool operator() (double first, double second)
  { return (fabs(first-second)<5.0); }
};

int main ()
{
  double mydoubles[]={ 12.15,  2.72, 73.0,  12.77,  3.14,
                       12.77, 73.35, 72.25, 15.3,  72.25 };
  std::list<double> mylist (mydoubles,mydoubles+10);

  mylist.sort();             //  2.72,  3.14, 12.15, 12.77, 12.77,
                             // 15.3,  72.25, 72.25, 73.0,  73.35

  mylist.unique();           //  2.72,  3.14, 12.15, 12.77
                             // 15.3,  72.25, 73.0,  73.35

  mylist.unique (same_integral_part);  //  2.72,  3.14, 12.15
                                       // 15.3,  72.25, 73.0

  mylist.unique (is_near());           //  2.72, 12.15, 72.25

  std::cout << "mylist contains:";
  for (std::list<double>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

输出:
mylist contains: 2.72 12.15 72.25

✥ 复杂度



容器大小减1线性。

☣ 迭代器的有效性



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

⇄ 数据竞争


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

☂ 异常安全性



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

🍄  另请参阅



list::remove 按值删除元素(公众成员函数)
list::remove_if 移除满足条件的元素(公众成员函数)
list::push_back 在末尾添加元素(公众成员函数)
list::push_front 在开头插入元素(公众成员函数)
list::erase 删除元素(公众成员函数)

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