find_if的替代版本可以找到全部,而不仅仅是第一个? [英] Alternative version of find_if which finds all, not just the first?
本文介绍了find_if的替代版本可以找到全部,而不仅仅是第一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有std::find_if
的替代版本,该替代版本返回所有找到的元素的迭代器,而不仅仅是第一个元素?
Is there an alternative version of std::find_if
that returns an iterator over all found elements, instead of just the first one?
示例:
bool IsOdd (int i) {
return ((i % 2) == 1);
}
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
std::vector<int>::iterator it = find_if(v.begin(), v.end(), IsOdd);
for(; it != v.end(); ++it) {
std::cout << "odd: " << *it << std::endl;
}
推荐答案
您可以使用for
循环:
for (std::vector<int>:iterator it = std::find_if(v.begin(), v.end(), IsOdd);
it != v.end();
it = std::find_if(++it, v.end(), IsOdd))
{
// ...
}
或者,您可以将条件和操作放入函子(仅在条件为true时才执行操作),只需使用std::foreach
.
Alternatively, you can put your condition and action into a functor (performing the action only if the condition is true) and just use std::foreach
.
这篇关于find_if的替代版本可以找到全部,而不仅仅是第一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文