Студопедия.Орг Главная | Случайная страница | Контакты | Мы поможем в написании вашей работы!  
 

Пример 2. Алгоритмы и функциональные объекты



#include <functional.h>#include <deque.h>#include <algorithm.h>#include <iostream.h>#include <iomanip.h>//Create a new function object from unary_function template<class Arg> class div2: public unary_function<Arg, Arg> { public: Arg operator()(const Arg& arg) { return arg/2; } };int main(int argc, char* argv[]){//Initialize a deque with an array of intsint arr1[5] = {99, 264, 126, 330, 132};int arr2[5] = {280, 105, 220, 84, 210};deque<int> d1(arr1+0, arr1+5), d2(arr2+0, arr2+5);deque<int>::iterator i1;for(i1 = d1.begin(); i1!= d1.end(); i1++) cout << setw(6) << *i1 << " ";cout << endl;for(i1 = d2.begin(); i1!= d2.end(); i1++) cout << setw(6) << *i1 << " ";cout << endl;transform(d1.begin(), d1.end(), d2.begin(), d1.begin(), multiplies<int>());cout << "Multiplies result" << endl;for(i1 = d1.begin(); i1!= d1.end(); i1++) cout << setw(6) << *i1 << " ";cout << endl;cout << "Div result" << endl;transform(d2.begin(), d2.end(), d2.begin(), div2<int>());for(i1 = d2.begin(); i1!= d2.end(); i1++) cout << setw(6) << *i1 << " ";cout << endl;return 0;}

The transform algorithm has two forms. The first form applies unary operation op to each element of the range [first, last), and sends the result to the output iterator result. If the output iterator (result) is the same as the input iterator used to traverse the range, transform performs its transformation in place.

The second form of transform applies a binary operation, binary_op, to corresponding elements in the range [first1, last1) and the range that begins at first2, and sends the result to result. For example, transform can be used to add corresponding elements in two sequences, and store the set of sums in a third. The algorithm assumes, but does not check, that the second sequence has at least as many elements as the first sequence. Note that the output iterator result can be a third sequence, or either of the two input sequences.

transform (InputIterator first, InputIterator last, OutputIterator result, UnaryOperation op);transform (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryOperation binary_op);

Функциональный объект unary_function определен след. образом:

#include <functional>template <class Arg, class Result>struct unary_function{ typedef Arg argument_type; typedef Result result_type;};




Дата публикования: 2015-01-13; Прочитано: 213 | Нарушение авторского права страницы | Мы поможем в написании вашей работы!



studopedia.org - Студопедия.Орг - 2014-2024 год. Студопедия не является автором материалов, которые размещены. Но предоставляет возможность бесплатного использования (0.006 с)...