1

有什么方法可以计算 STL 中 remove_if 函数删除的次数?

具体来说,我将前向和后向迭代器分别传递给整数向量,并将 lambda 作为第三个参数作为 remove_if 的比较值,以确定是否应根据向量中的值删除向量。我想知道是否有办法知道 remove_if 之后删除的向量数量。

另外,作为一个附带问题:我动态地声明了这些向量,所以我不确定在这些向量上调用 remove_if 是否是不好的做法。

4

2 回答 2

5

计算 remove_if 之前和之后的元素个数。

auto old_size = list.size();
auto new_end = std::remove_if(list.begin(), list.end(), ...);
auto new_size = std::distance(list.begin(), new_end);
auto deletions = old_size - new_size;
于 2016-03-17T04:23:39.447 回答
1

更长的答案(尽管@kukac 的)是正确的。

remove和 ( remove_if) 实际上并不从向量中删除元素;他们只是将它们打乱到最后,并将迭代器返回到“已删除”元素的开头。要真正摆脱它们,您调用erase. 这被称为“擦除删除习语”,并且有很多关于此的帖子。

像这样(未编译的代码):

vector<int> v = {1,2,3,4,5}; // v.size() == 5
auto it = remove_if(v.begin(), v.end(), is_odd);
// now v looks something like this: {2,4,5,1,3}
//   the v.size() is still == 5
//   and it "points to" '5'
v.erase(it, v.end()); // erase all the elements that were "removed"
// now v looks something like this: {2,4}
//   the v.size() is now == 2
于 2016-03-17T05:50:19.807 回答