列表::在C++ STL中,ReaveE.(和)::

清单 C++中使用的容器以非连续的方式存储数据,通常,数组和向量本质上是连续的,因此插入和删除操作与列表中的插入和删除选项相比更昂贵。

null
列表::删除()

remove()函数用于从列表中删除与作为函数参数给定的值相对应的所有值 语法:

listname.remove(value)Parameters :The value of the element to be removed is passed as the parameter.Result :Removes all the elements of the containerequal to the value passed as parameter

例如:

Input  : list list{1, 2, 3, 4, 5};         list.remove(4);Output : 1, 2, 3, 5Input  : list list{1, 2, 2, 2, 5, 6, 7};         list.remove(2);Output : 1, 5, 6, 7

错误和异常

  1. 如果传递的值与列表类型不匹配,则显示错误。
  2. 如果列表功能的值和元素之间的比较没有引发任何异常,则不显示异常引发保证。

CPP

// CPP program to illustrate
// Implementation of remove() function
#include <iostream>
#include <list>
using namespace std;
int main()
{
list< int > mylist{ 1, 2, 2, 2, 5, 6, 7 };
mylist. remove (2);
for ( auto it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
}


输出:

1 5 6 7

列表::删除_if()

remove_if()函数用于从列表中删除与 谓语 或作为函数参数给出的条件。该函数遍历列表容器的每个成员,并删除谓词返回true的所有元素。 语法:

listname.remove_if(predicate)Parameters :The predicate in the form of aa function pointeror function object is passed as the parameter.Result :Removes all the elements of the containerwhich return true for the predicate.

例如:

Input  : list list{1, 2, 3, 4, 5};         list.remove_if(odd);Output : 2, 4Input  : list list{1, 2, 2, 2, 5, 6, 7};         list.remove_if(even);Output : 1, 5, 7

错误和异常

  1. 如果谓词函数功能不引发任何异常,则不显示异常引发保证。

CPP

// CPP program to illustrate
// Implementation of remove_if() function
#include <iostream>
#include <list>
using namespace std;
// Predicate implemented as a function
bool even( const int & value) { return (value % 2) == 0; }
// Main function
int main()
{
list< int > mylist{ 1, 2, 2, 2, 5, 6, 7 };
mylist.remove_if(even);
for ( auto it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
}


输出:

1 5 7

申请: 给定一个整数列表,从列表中删除所有素数并打印列表。

Input  : 2, 4, 6, 7, 9, 11, 13Output : 4, 6, 9

CPP

// CPP program to illustrate
// Application of remove_if() function
#include <iostream>
#include <list>
using namespace std;
// Predicate implemented as a function
bool prime( const int & value)
{
int i;
for (i = 2; i < value; i++) {
if (value % i == 0) {
return false ;
}
}
if (value == i) {
return true ;
}
}
// Main function
int main()
{
list< int > mylist{ 2, 4, 6, 7, 9, 11, 13 };
mylist.remove_if(prime);
for ( auto it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
}


输出:

4 6 9

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享