CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Aug 2005
    Location
    San Diego, CA
    Posts
    1,054

    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.

  2. #2
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470

    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
  •  





Click Here to Expand Forum to Full Width

Featured