C++ STL 中的 list_remove() 和 list remove_if()
本任务旨在展示 C++ STL 中 list remove() 和 list remove_if() 函数的功能。
什么是 STL 中的 List?
List 是一种容器,允许在序列中的任何位置进行常数时间插入和删除。List 以双向链表的形式实现。List 允许非连续内存分配。与数组、向量和双端队列相比,List 在任何位置插入、提取和移动元素方面性能更好。在 List 中,对元素的直接访问速度较慢,并且 List 类似于 forward_list,但 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
可以遵循的方法
首先,我们声明 List。
然后我们打印 List。
然后我们定义 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() 函数?
此函数用于移除返回值为真的谓词或返回值为真的条件(作为参数传递)的值。
语法
listname.remove_if(predicate)
参数
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP