Exercise 11. Algorithms from scratch.

Open this wandbox (b, b, b). You'll see an implementation of std::find and std::find_if.

1. Fill in the blanks in "count.h" to implement std::count and std::count_if. Run the test cases; they should pass.

2. Can you reimplement std::find in terms of std::find_if, and reimplement std::count in terms of count_if? (Yes.) What are the advantages and disadvantages (if any) of doing so?

3. The provided implementation of std::count returns size_t. The Standard Library's version actually returns iterator_traits<It>::difference_type. Adjust your implementation to return difference_type as well.

If you haven't worked much with template programming before, you might run into the following syntax error:

error: missing 'typename' prior to dependent type name 'std::iterator_traits<It>::difference_type'
std::iterator_traits<It>::difference_type count_if(It first, It last, const F& predicate)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
typename
or with GCC,
error: need 'typename' before 'std::iterator_traits<_Iterator>::difference_type'
because 'std::iterator_traits<_Iterator>' is a dependent scope
 std::iterator_traits<It>::difference_type count_if(It first, It last, const F& predicate)
 ^~~
Both compilers are good enough to suggest the correct fix: to insert the keyword typename.

4. Look at this wandbox (backup). It has a version of find where the "value" parameter is of type const iterator_traits<It>::value_type& instead of const T&. What are some disadvantages of this version? Advantages? Which would you expect to be faster for the use-case in that wandbox's main routine?

5. (Optional) Measure and find out which version is faster, and how many elements you need in the vector in order for one to overtake the other. Which one makes more sense for the Standard Library to provide?

You're done with this set of exercises! Sit back and relax, or optionally, read the following paper and StackOverflow question.