Click to See Complete Forum and Search --> : return type for count algorithm


kempofighter
June 16th, 2008, 02:02 PM
Hello. I was writing a program and decided to use the std::count algorithm. My program seems to compile as I have written it, but I have a trivia question about the return type.


template <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count ( ForwardIterator first, ForwardIterator last, const T& value );

The question is, why is the return value a difference between two iterators instead of just an integer? I don't see how a ptrdiff_t type makes any sense as a return value for this algorithm. I saw that in Josuttis' text book (the C++ std library) he just uses an int to hold the return value. That's great, but isn't there an implicit cast happening if you do this?

int num = std::count(begin, end, 5);

Does the implementation make a new container with the values that pass the comparison or predicate and then determine the count by subtracting the pointers? If so, I wonder if I'd be better off writing my own for loop to do the work.

Graham
June 16th, 2008, 02:11 PM
Because difference_type is guaranteed to be large enough to hold the answer (c.end() - c.begin() for a maximally populated container).