C++ transform 淺析,transform淺析

來源:互聯網
上載者:User

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;  }  


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.