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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP