O'Reilly logo

C++ Cookbook by Jeff Cogswell, Jonathan Turkanis, Christopher Diggins, D. Ryan Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required