在不使用std::erase的情况下,可以使用std::remove_if来移除容器中满足特定条件的元素。下面是一个使用std::remove_if的用例,并提供了代码示例来说明解决方法:
假设有一个整数向量nums,现在要移除向量中所有小于等于5的元素。
#include
#include
#include
int main() {
std::vector nums = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};
// 使用std::remove_if移除小于等于5的元素
nums.erase(std::remove_if(nums.begin(), nums.end(), [](int num) {
return num <= 5;
}), nums.end());
// 输出移除后的向量
for (int num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
在以上代码中,我们使用std::remove_if结合lambda表达式来移除nums向量中所有小于等于5的元素。首先,我们调用std::remove_if(nums.begin(), nums.end(), [](int num) { return num <= 5; })来返回一个指向移除后的新的end迭代器。然后,我们使用nums.erase来擦除从新的end迭代器到向量结束的所有元素。
最后,我们输出移除后的向量,结果为:7 9 6 8 10。可以看到,原始向量中小于等于5的元素已经被移除。