說明
簡而言之堡掏,transform
是用來做轉(zhuǎn)換的放棒。
轉(zhuǎn)換有兩種:一元轉(zhuǎn)換和二元轉(zhuǎn)換套利。
一元轉(zhuǎn)換是對容器給定范圍內(nèi)的每個元素做某種一元運算后放在另一個容器里。只涉及一個參與轉(zhuǎn)換運算的容器父晶。
有4個參數(shù),前2個指定要轉(zhuǎn)換的容器的起止范圍弄跌,第3個參數(shù)是結(jié)果存放容器的起始位置甲喝,第4個參數(shù)是一元運算。
函數(shù)簽名是:
template< class InputIt, class OutputIt, class UnaryOperation >
OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first,
UnaryOperation unary_op );
二元轉(zhuǎn)換是對兩個容器給定范圍內(nèi)的每個元素做二元運算后放在另一個容器里铛只。涉及兩個參與轉(zhuǎn)換運算容器埠胖。
有5個參數(shù),前2個指定參與轉(zhuǎn)換的第1個容器的起止范圍淳玩,第3個參數(shù)是轉(zhuǎn)換的第2個容器的起始位置直撤,
第4個參數(shù)是結(jié)果存放容器的起始位置,第5個參數(shù)是二元運算蜕着。
函數(shù)簽名是:
template< class InputIt1, class InputIt2, class OutputIt, class BinaryOperation >
OutputIt transform( InputIt1 first1, InputIt1 last1, InputIt2 first2,
OutputIt d_first, BinaryOperation binary_op );
頭文件
#include <algorithm>
例子:對字符串進行大小寫轉(zhuǎn)換
#include <iostream>
#include <cctype>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
std::string str = "Hello, World!";
cout << str << endl;
// toupper
std::string strUpper(str.length(), ' ');
std::transform(str.begin(), str.end(), strUpper.begin(), std::toupper);
cout << strUpper << endl;
// tolower
std::transform(str.begin(), str.end(), str.begin(), std::tolower);
cout << str << endl;
system("pause");
return 0;
}
結(jié)果:
Hello, World!
HELLO, WORLD!
hello, world!
這是一元轉(zhuǎn)換谋竖。
例子:兩個數(shù)組元素分別相加
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> v1 = {10, 20, 30, 40, 50};
std::vector<int> v2 = { 1, 2, 3, 4, 5 };
std::vector<int> result(5);
std::transform(v1.begin(), v1.end(), v2.begin(), result.begin(), std::plus<int>());
for (int i : result) {
std::cout << i << "\t";
}
std::cout << std::endl;
return 0;
}
結(jié)果:
11 22 33 44 55
這是二元轉(zhuǎn)換。
參考
http://www.cplusplus.com/reference/algorithm/transform/
https://zh.cppreference.com/w/cpp/algorithm/transform