A number of algorithms provided in the C++ Standard Library accept functions as arguments. A simple example is the algorithm std::for_each(), which invokes a function, passed as an argument, on each value held in a container. For example, the following code fragment applies the printElement() function to produce output describing each element in a list of integer values:
void printElement(int value) { std::cout << "The list contains " << value << std::endl; } int main() { std::list<int> aList; ... std::for_each(aList.begin(), aList.end(), printElement); }
Binary functions take two arguments, and are often applied to values from two different sequences. For example, suppose we have a list of strings and a list of integers. For each element in the first list we wish to replicate the string the number of times given by the corresponding value in the second list. We can perform this easily using the function std::transform() from the C++ Standard Library. First, we define a binary function with the desired characteristics:
std::string stringRepeat(const std::string& base, int number) // replicate base the given number of times { std::string result; // initially the result is empty while (number--) result += base; return result; }
The following call on std::transform() then produces the desired effect:
std::list<string> words; std::list<int> counts; ... std::transform(words.begin(), words.end(), counts.begin(), words.begin(), stringRepeat);
Transforming the strings "one", "two", "three" with the values 3, 2, 3 would yield the result "oneoneone", "twotwo", "threethreethree".