前向迭代器与多个绑定相结合的迭代速度太快

ForwardIterator combined with multiple bind's is iterating too fast

本文关键字:迭代 速度 相结合 绑定 迭代器      更新时间:2023-10-16

我想遍历 int s 的vector并删除所有偶数。

例:

std::vector<int> v = {5,2,9,3,8}
auto it = std::remove_if(v.begin(),v.end(), 
    std::bind(std::bind(std::equal_to<int>(),_1,0),
    std::bind(std::modulus<int>(),_1,2)));

预期结果应为 {5,9,3}但它是{5,8,9,3,8}

我认为在执行绑定和删除中的所有功能之前,迭代器已经处于最后。

我知道如何以不同的方式解决它,但我想知道如何使用嵌套形式以及它如何与迭代器一起使用

在VS2015中,您的代码留下包含{5, 9, 3, 3, 8}的v

std::remove_if()返回一个迭代器到vector中第一个未使用的元素,使用它来截断vector

v.erase(it, v.end());

之后,v包含 {5, 9, 3}


附带说明一下,如果你想使用 lambda 而不是 bind你可以这样做:

std::vector<int> v = { 5, 2, 9, 3, 8 };
auto it = std::remove_if(v.begin(), v.end(), [](int val) { return val % 2 == 0; });
v.erase(it, v.end());