|
-
June 16th, 2008, 02:02 PM
#1
return type for count algorithm
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.
Code:
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?
Code:
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.
-
June 16th, 2008, 02:11 PM
#2
Re: return type for count algorithm
Because difference_type is guaranteed to be large enough to hold the answer (c.end() - c.begin() for a maximally populated container).
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|