微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 找到满足条件的第n个元素?

有几个std :: algorithm / lambda函数访问满足给定条件的第n个元素.因为std :: find_if将访问第一个,所以有一个等价物来找到第n个?

解决方法

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

http://ideone.com/EZLLdL

原文地址:https://www.jb51.cc/c/113008.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐