📜  C++ STL中的list :: remove()和list :: remove_if()

📅  最后修改于: 2021-05-30 03:53:22             🧑  作者: Mango

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

list :: remove()

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 container
equal to the value passed as parameter

例子:

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

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

错误和异常

  1. 如果传递的值与列表类型不匹配,则显示错误。
  2. 如果列表功能的值和元素之间的比较未引发任何异常,则不显示异常引发保证。
// CPP program to illustrate
// Implementation of remove() function
#include 
#include 
using namespace std;
  
int main()
{
    list 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
list :: remove_if()

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

句法 :

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

例子:

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

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

错误和异常

  1. 如果谓词函数功能未引发任何异常,则不显示任何引发异常的保证。
// CPP program to illustrate
// Implementation of remove_if() function
#include 
#include 
using namespace std;
  
// Predicate implemented as a function
bool even(const int& value) { return (value % 2) == 0; }
  
// Main function
int main()
{
    list 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, 13
Output : 4, 6, 9
// CPP program to illustrate
// Application of remove_if() function
#include 
#include 
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;
            ;
            break;
        }
    }
    if (value == i) {
        return true;
        ;
    }
}
  
// Main function
int main()
{
    list 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
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”