解决方法
您需要创建一个有状态谓词,它将对实例数进行计数,然后在达到预期计数时完成.现在的问题是,在算法评估过程中,无法确定谓词将被复制多少次,所以您需要将该状态保留在谓词本身之外,这使得它有点丑陋,但可以做:
- 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);
- });
- }