在迭代器中计数所有元素的最佳方式是什么?
我想要代码相当于此
template<typename T,typename S,S val> struct ConstantFunctor : unary_function<T,S> {S operator()(const T&) const {return val;}}; template<typename T> struct TrueFunctor : ConstantFunctor<T,bool,true>{}; ... count_if(c.begin(),c.end(),TrueFunctor());
最好的方法是什么?
我可以使用boost :: lambda :: constant(true),但也许有一些更清晰的东西.
解决方法
如果要计数范围内的所有元素.那么你可以使用
std::distance
,从
<iterator>
标题,像这样:
int count = std::distance(begin(c),end(c));
应该够了
online doc说关于std :: distance:
原文地址:https://www.jb51.cc/c/111592.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。