相关文章推荐

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删除元素

vector中的remove_if使用: remove_if(ivec.begin(), ivec.end(), function)作用:删除满足function函数的元素。实例如下:#include <iostream>#include <vector>#include <algorithm>using namespace std;bool compare(int d){ re 前两个参数:表示迭代的起始位置和这个起始位置所对应的停止位置【迭代器】。 最后一个参数:传入一个回调函数,如果回调函数返回为真,则将当前所指向的元素移到尾部。 返回值:被移动到某个区域的首个目标元素 iterator,将此删除即实现了将要删除的元素删除的目的 #include <algorithm> 此函数无法删除元素,因为使用的是迭代器,不能删除元素,只能把要删除的元素移到容器末尾【不一定,如果有多个目标元
remove_if 是一个有很欺骗性的函数。 我们进入它的源码看看它的内部实现remove_if(_ForwardIterator __first, _ForwardIterator __last, _Predicate __pred) __first = _VSTD::find_if<_ForwardIterator, typename add_lvalue_reference<_P
remove_if是一个算法函数,用于从容器中移除满足特定条件的元素。它需要两个迭代器参数和一个谓词,谓词用于定义要移除的元素条件。 下面是remove_if函数的基本用法示例: ```cpp #include <iostream> #include <vector> #include <algorithm> bool isOdd(int num) { return num % 2 != 0; int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; // 使用remove_if移除奇数 numbers.erase(std::remove_if(numbers.begin(), numbers.end(), isOdd), numbers.end()); // 输出移除奇数后的结果 for (const auto& num : numbers) { std::cout << num << " "; std::cout << std::endl; return 0; 在上面的示例中,我们定义了一个isOdd函数作为谓词,用于判断一个整数是否为奇数。然后我们使用remove_if函数将容器中的奇数移除,并使用erase函数从容器中擦除这些元素。最后,我们遍历容器并输出结果。 输出结果为: 这是移除奇数后的结果。 希望这能帮助你理解remove_if的用法。如果你还有其他问题,请随时提问!
 
推荐文章