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<typename 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.
The distance() function in C++ helps find the distance between two iterators. In other words, we can use this function to calculate the number of elements present between the two iterators. This function is available in the <iterator> header file.
If two unrelated iterators (including pointers) are subtracted, the operation results in undefined behavior [ISO/IEC 14882-2014]. Do not subtract two iterators (including pointers) unless both point into the same container or one past the end of the same container.
we can use == and != to compare to valid iterators into any of the library containers. The section also tells us that iterators for string and vector support relational operators (aka iterator arithmetic) which include >, >=, <, <=.
Syntax: std::distance(InputIterator first, InputIterator last) Here, first and last are input iterators between which we have to calculate distance. Returns: The number of elements between first and last.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With