C ++ STL中的list_remove()和list remove_if()

2023年11月17日09:59:39

给出的任务是显示STL中C ++中的功能列表remove()和list remove_if()函数。

什么是STL中的列表?

列表是允许在任何地方按顺序进行恒定时间插入和删除的容器。列表被实现为双链表。列表允许不连续的内存分配。与数组,向量和双端队列相比,列表在容器中的任何位置执行元素的插入提取和移动效果更好。在列表中,对元素的直接访问很慢,并且列表与forward_list相似,但是转发列表对象是单个链接列表,并且只能迭代转发。

什么是remove()?

此函数用于删除参数中传递给函数的给定值。

语法

listname.remove(val);

参数

val-它定义了要删除的值。

示例

Input List: 1 2 3 3 4 5
Output New List: 1 2 4 5
In this List element 3 is removed.

Input List: 5 6 7 8 8 8 9
Output New List: 5 7 8 8 8 9
In this list element 6 in removed

可以遵循的方法

  • 首先,我们声明列表。

  • 然后我们打印列表。

  • 然后我们定义remove()函数。

通过使用上述方法,我们可以删除给定的元素。

示例

// C++ code to demonstrate the working of list remove( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
int main ( ){
   List<int> list = { 21, 24, 28, 26, 27, 25 };
   // print the list
   cout<< " list: ";
   for( auto x = list.begin( ); x != list.end( ); ++x)
      cout<< *x << " ";
   // defining remove( ) function
   list.remove(27);
   cout<< " New List:”;
   for( x = list.begin( ); x != list.end( ); ++x)
      cout<<' " " << *x;
   return 0;
}

输出结果

如果我们运行上面的代码,那么它将生成以下输出

Input - List: 21 24 28 26 27 25
Output - New List: 21 24 28 26 25
Input – List: 45 46 47 48 49 50
Output – New List: 45 46 48 49 50

什么是remove_if()函数?

此函数用于删除返回谓词为true或对于作为参数传递的条件返回true的值。

语法

listname.remove_if(predicate)

参数

谓词-它定义一个条件作为参数传递。

示例

Input – List: 5 6 7 8 9 10
Output – New List: 5 7 9
In this list we remove all the even elements.

Input – List:5 10 15 20 25 30
Output – New List: 5 15 25
In this List we remove all the elements which is divisible by 10.

可以遵循的方法

  • 首先,我们声明谓词函数。

  • 然后我们声明列表。

  • 然后我们打印列表。

  • 然后我们声明remove_if()函数。

通过使用上述方法,我们可以删除任何给定条件下的元素。在声明remove_if()函数时,我们将谓词作为参数传递。

示例

// C++ code to demonstrate the working of list remove_if( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
Bool div3( const int& val){
   return( val % 3) == 0);
}
int main( ){
   List<int> list = { 2, 3, 4, 15, 9, 7, 21, 24, 13 };
   cout<< " List: ";
   for( auto x = list.begin( ); x != list.end( ); ++x)
      cout<< *x << " ";
   // declaring remove_if( ) function
   list.remove_if(div3);
   cout<< " New List:”;
   for( x= list.begin( ); x != end( ); ++x)
      cout<< " " << *x;
   return 0;
}

输出结果

如果我们运行上面的代码,那么它将生成以下输出

Input – List: 2 3 4 15 9 7 21 24 13
Output – New List: 2 4 7 13

  • 更新时间:2023年11月17日09:59:39 ,共 2174 字。