remove_if使用示例

vector中的remove_if使用:

    remove_if(ivec.begin(), ivec.end(), function)

作用:删除满足function函数的元素。实例如下:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool compare(int d)
{
    return d < 30;
}

int main()
{
    int myints[] = { 15, 36, 7, 17, 20, 39, 4, 1 };
    vector<int> ivec(myints, myints + 8);   // 15 36 7 17 20 39 4 1

    ivec.erase(remove_if(ivec.begin(), ivec.end(), compare), ivec.end());    //删除满足compare条件的元素

    for (vector<int>::iterator it = ivec.begin(); it != ivec.end(); ++it)
        cout << *it << endl;     //36 39

    return 0;
}

vector初始化,请参考我的博客:
c++ vector(向量)使用方法详解(顺序访问vector的多种方式)

vector删除,请参考我的博客:
vector删除元素

这三个函数是 STL 算法中用于删除元素的函数。它们的作用分别是: - `remove_if`:删除满足指定条件的元素,返回指向新的逻辑结尾的迭代器。 - `remove_copy`:将满足指定条件的元素拷贝到另一个容器中,返回指向新的逻辑结尾的迭代器。 - `remove_copy_if`:将不满足指定条件的元素拷贝到另一个容器中,返回指向新的逻辑结尾的迭代器。 下面是它们的用法和示例: ```cpp #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { // remove_if vector<int> v1{1, 2, 3, 4, 5}; auto it1 = remove_if(v1.begin(), v1.end(), [](int x) { return x % 2 == 0; }); v1.erase(it1, v1.end()); for (int x : v1) { cout << x << " "; // 输出 1 3 5 } cout << endl; // remove_copy vector<int> v2{1, 2, 3, 4, 5}; vector<int> v3; remove_copy(v2.begin(), v2.end(), back_inserter(v3), [](int x) { return x % 2 == 0; }); for (int x : v3) { cout << x << " "; // 输出 1 3 5 } cout << endl; // remove_copy_if vector<int> v4{1, 2, 3, 4, 5}; vector<int> v5; remove_copy_if(v4.begin(), v4.end(), back_inserter(v5), [](int x) { return x % 2 == 0; }); for (int x : v5) { cout << x << " "; // 输出 1 3 5 } cout << endl; return 0; } ``` 注意,这三个函数并不真正删除容器中的元素,而是返回指向新的逻辑结尾的迭代器。如果要真正删除元素,需要结合容器的 `erase` 函数使用。此外,`remove_copy` 和 `remove_copy_if` 会将满足条件的元素拷贝到另一个容器中,因此要注意目标容器的类型和大小。在示例中,使用了 `back_inserter` 函数将元素插入 `vector` 的尾部。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值