使用擦除-删除_if成语 [英] Using erase-remove_if idiom
问题描述
假设我有std::vector<std::pair<int,Direction>>
.
我正在尝试使用"ease-remove_if"惯用语从向量中删除配对.
I am trying to use erase-remove_if idiom to remove pairs from the vector.
stopPoints.erase(std::remove_if(stopPoints.begin(),
stopPoints.end(),
[&](const stopPointPair stopPoint)-> bool { return stopPoint.first == 4; }));
我要删除.first值设置为4的所有对.
I want to delete all pairs that have .first value set to 4.
在我的示例中,我有一对:
In my example I have pairs:
- 4, Up
- 4, Down
- 2, Up
- 6, Up
但是,在我执行了remove-remove_if之后,剩下的仍然是:
However, after I execute erase-remove_if, I am left with:
- 2, Up
- 6, Up
- 6, Up
我在做什么错了?
推荐答案
正确的代码是:
stopPoints.erase(std::remove_if(stopPoints.begin(),
stopPoints.end(),
[&](const stopPointPair stopPoint)-> bool
{ return stopPoint.first == 4; }),
stopPoints.end());
您需要删除从std::remove_if
返回的迭代器开始到向量结尾的范围,而不仅仅是单个元素.
You need to remove the range starting from the iterator returned from std::remove_if
to the end of the vector, not only a single element.
为什么?"
-
std::remove_if
在向量内部交换元素,以便将所有与谓词不匹配的元素放入容器的开头.
std::remove_if
swaps elements around inside the vector in order to put all elements that do not match the predicate towards the beginning of the container.
-
然后返回指向第一个谓词匹配元素的迭代器.
std::vector::erase
需要删除从返回的迭代器到向量结尾的范围,以便删除所有与谓词匹配的元素 .
更多信息: 删除擦除的习语(维基百科) .
这篇关于使用擦除-删除_if成语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!