C++ 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 );
參數說明:
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; }
轉載于:https://www.cnblogs.com/jzdwajue/p/6917588.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的C++ transform 浅析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux下添加用户并赋予root权限
- 下一篇: s3c2440移植MQTT