开发者

How many elements are there between two iterators

What's the best way to count all elements in an iterator?

I want code equivalent to this

template<typename T,typename S,S val>
struct ConstantFunctor : unary_function<T,S>
{S operator()(const T&) const {return val;}};
template<typena开发者_StackOverflowme T>
struct TrueFunctor : ConstantFunctor<T,bool,true>{};
...
count_if(c.begin(),c.end(),TrueFunctor());

What's the best way to do that?

I can use boost::lambda::constant(true), but maybe there's something clearer.


If you want to count all elements in a range. then you can use std::distance, from the <iterator> header, like so:

int count = std::distance(begin(c), end(c));

It should be enough.

The online doc says about std::distance:

Calculates the number of elements between first and last.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜