7.10. Writing Your Own Algorithm

Problem

You need to execute an algorithm on a range and none of the standard algorithms meets your requirements.

Solution

Write your algorithm as a function template and advertise your iterator requirements with the names of your template parameters. See Example 7-10 for a variation on the copy standard algorithm.

Example 7-10. Writing your own algorithm

#include <iostream>
#include <istream>
#include <iterator>
#include <string>
#include <functional>
#include <vector>
#include <list>
#include "utils.h" // For printContainer(): see 7.10

using namespace std;

template<typename In, typename Out, typename UnPred>
Out copyIf(In first, In last, Out result, UnPred pred) {
   for ( ;first != last; ++first)
      if (pred(*first))
         *result++ = *first;
   return(result);
}

int main() {

   cout << "Enter a series of strings: ";
   istream_iterator<string> start(cin);
   istream_iterator<string> end; // This creates a "marker"
   vector<string> v(start, end);

   list<string> lst;

   copyIf(v.begin(), v.end(), back_inserter<list<string> >(lst),
      bind2nd(less<string>(), "cookie"));

   printContainer(lst);
}

A sample run of Example 7-10 will look something like this:

Enter a series of strings: apple banana danish eclaire
^Z
-----
apple banana

You can see that it only copies values less than “cookie” into the destination range.

Discussion

The standard library contains the copy function template, which copies elements from one range to another, but there is no standard version that takes a predicate and conditionally ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.