是否有几个std::algorithm/lambda function
访问nth
满足给定条件的元素。因为std::find_if
将访问第一个,所以是否有一个等价的找到那个nth
?
您需要创建一个有状态的谓词,该谓词将对实例的数量进行计数,然后在达到预期数量时完成。现在的问题是,在评估算法期间无法保证谓词将被复制多少次,因此您需要将该状态保持在谓词本身之外,这有点丑陋,但是您可以这样做:
iterator which;
{ // block to limit the scope of the otherwise unneeded count variable
int count = 0;
which = std::find_if(c.begin(), c.end(), [&count](T const & x) {
return (condition(x) && ++count == 6)
});
};
如果经常出现这种情况,并且您不关心性能,则可以编写一个谓词适配器,该适配器在内部为该计数创建一个shared_ptr并对其进行更新。同一适配器的多个副本将共享同一实际计数对象。
另一个选择是实施find_nth_if
,这可能会更简单。
#include <iterator>
#include <algorithm>
template<typename Iterator, typename Pred, typename Counter>
Iterator find_if_nth( Iterator first, Iterator last, Pred closure, Counter n ) {
typedef typename std::iterator_traits<Iterator>::reference Tref;
return std::find_if(first, last, [&](Tref x) {
return closure(x) && !(--n);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句