C++ transform 淺析,transform淺析
【摘要】
transform,一個區間元素交換函數。該函數用於實現容器元素的變換操作。有如下兩個使用原型,一個將迭代器區間[first,last)中元素,執行一元函數(有一個輸入變數)對象op操作,交換後的結果放在[result,result+(last-first))區間中。另一個將迭代器區間[first1,last1)的元素*i,依次與[first2,first2+(last-first))的元素*j,執行二元函數(有兩個輸入變數)操作binary_op(*i,*j),交換結果放在[result,result+(last1-first1))。
【本文】
函數原型:
template < class InputIterator, class OutputIterator, class UnaryOperator > OutputIterator transform ( InputIterator first1, InputIterator last1, OutputIterator result, UnaryOperator op );
template < class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperator > OutputIterator transform ( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryOperator binary_op );
參數說明:
first1, last1
指出要進行元素變換的第一個迭代器區間 [first1,last1)。
first2
指出要進行元素變換的第二個迭代器區間的首個元素的迭代器位置,該區間的元素個數和第一個區間相等。
result
指出變換後的結果存放的迭代器區間的首個元素的迭代器位置
op
用一元函數對象op作為參數,執行其後返回一個結果值。它可以是一個函數或對象內的類重載operator()。
binary_op
用二元函數對象binary_op作為參數,執行其後返回一個結果值。它可以是一個函數或對象內的類重載operator()。
程式樣本:
#include <iostream> #include <algorithm> #include <vector> using namespace std; int op_increase (int i) { return ++i; } int op_sum (int i, int j) { return i+j; } int main () { vector<int> first; vector<int> second; vector<int>::iterator it; // set some values: for (int i=1; i<6; i++) first.push_back (i*10); // first: 10 20 30 40 50 second.resize(first.size()); // allocate space transform (first.begin(), first.end(), second.begin(), op_increase); // second: 11 21 31 41 51 transform (first.begin(), first.end(), second.begin(), first.begin(), op_sum); // first: 21 41 61 81 101 cout << "first contains:"; for (it=first.begin(); it!=first.end(); ++it) cout << " " << *it; cout << endl; return 0; }
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。