为什么vector的remove_if实际上并没有删除元素,而要配合erase使用

Erase-Remove idiom是C++中用于从容器中删除满足特定条件元素的常见编程技巧。它不直接删除元素,而是将不符合条件的元素移到容器前面,保持相对顺序,然后通过容器自身的erase成员函数来实际移除元素。这种方法不适用于返回const迭代器的容器,如set。
摘要由CSDN通过智能技术生成

Erase–remove idiom



Motivation[edit]

A common programming task is to remove all elements that have a certain value or fulfill a certain criterion from a collection. In C++, this could be achieved using a hand-written loop. It is, however, preferred to use an algorithm from the C++ Standard Library for such tasks.[1][2][3]

The algorithm library provides the remove and remove_if algorithms for this. Because these algorithms operate on a range of elem

这三个函数是 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、付费专栏及课程。

余额充值