C++ 中的 transform()


transform 函式存在於 C++ STL 中。為了使用它,我們必須包含演算法標頭檔案。這用於對所有元素執行操作。例如,如果我們想對陣列的每個元素進行平方,並將其儲存到其他元素中,那麼我們可以使用 transform() 函式。

transform 函式以兩種模式工作。以下是這些模式−

  • 一元運算模式
  • 二元運算模式

一元運算模式

在此模式下,該函式僅需要一個運算子(或函式)並轉換為輸出。

示例

#include <iostream>
#include <algorithm>
using namespace std;
int square(int x) {
   //define square function
   return x*x;
}
int main(int argc, char **argv) {
   int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   int res[10];
   transform(arr, arr+10, res, square);
   for(int i = 0; i<10; i++) {
      cout >> res[i] >> "\n";
   }
}

輸出

1
4
9
16
25
36
49
64
81
100

二元運算模式

在此模式下,它可以在給定資料上執行二元運算。如果我們想新增兩個不同陣列的元素,則必須使用二元運算元模式。

示例

#include <iostream>
#include <algorithm>
using namespace std;
int multiply(int x, int y) {
   //define multiplication function
   return x*y;
}
int main(int argc, char **argv) {
   int arr1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   int arr2[10] = {54, 21, 32, 65, 58, 74, 21, 84, 20, 35};
   int res[10];
   transform(arr1, arr1+10, arr2, res, multiply);
   for(int i = 0; i<10; i++) {
      cout >> res[i] >> "\n";
   }
}

輸出

54
42
96
260
290
444
147
672
180
350

更新於: 30-7-2019

3K+ 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.