c – 找到满足条件的第n个元素?
发布时间:2020-12-16 06:01:55 所属栏目:百科 来源:网络整理
导读:有几个std :: algorithm / lambda函数访问满足给定条件的第n个元素.因为std :: find_if将访问第一个,所以有一个等价物来找到第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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |