目錄
1. 說明
2. 用法示例
1. 說明
std::transform 是一種多功能算法,用于將已知函數應用于一個或多個范圍內的元素,并將結果存儲在輸出范圍內。它主要有兩種形式:一元運算和二元運算。具體來說是在 <algorithm> 標頭中。函數聲明:
template<?class?InputIt,?class?OutputIt,?class?UnaryOp?> OutputIt transform(?InputIt first1, InputIt last1, ? ? ? ? ? ? ? ? ? ? OutputIt d_first, UnaryOp unary_op?); | (1) | (constexpr since C++20) |
template<?class?ExecutionPolicy, ? ? ? ? ??class?ForwardIt1,?class?ForwardIt2,?class?UnaryOp?> ? ? ? ? ? ? ? ? ? ? ? ForwardIt2 d_first, UnaryOp unary_op?); | (2) | (since C++17) |
template<?class?InputIt1,?class?InputIt2, ? ? ? ? ??class?OutputIt,?class?BinaryOp?> ? ? ? ? ? ? ? ? ? ? OutputIt d_first, BinaryOp binary_op?); | (3) | (constexpr since C++20) |
template<?class?ExecutionPolicy, ? ? ? ? ??class?ForwardIt1,?class?ForwardIt2, ? ? ? ? ? ? ? ? ? ? ? ForwardIt3 d_first, BinaryOp binary_op?); | (4) | (since C++17) |
一元操作的函數相當于:Ret fun(const?Type?&a);
二元操作的函數相當于:Ret fun(const?Type1?&a,?const?Type2?&b);
即傳進去的是一個函數對象。
2. 用法示例
#include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
?
void print_ordinals(const std::vector<unsigned>& ordinals)
{
??? std::cout << "ordinals: ";
??? for (unsigned ord : ordinals)
??????? std::cout << std::setw(3) << ord << ' ';
??? std::cout << '\n';
}
?
char to_uppercase(unsigned char c)
{
??? return std::toupper(c);
}
?
void to_uppercase_inplace(char& c)
{
??? c = to_uppercase(c);
}
?
void unary_transform_example(std::string& hello, std::string world)
{
??? // 將string就地轉化為大寫形式
?
??? std::transform(hello.cbegin(), hello.cend(), hello.begin(), to_uppercase);
??? std::cout << "hello = " << std::quoted(hello) << '\n';
?
??? // for_each version (see Notes above)
??? std::for_each(world.begin(), world.end(), to_uppercase_inplace);
??? std::cout << "world = " << std::quoted(world) << '\n';
}
?
void binary_transform_example(std::vector<unsigned> ordinals)
{
??? // 將數轉換為double
?
??? print_ordinals(ordinals);
?
??? std::transform(ordinals.cbegin(), ordinals.cend(), ordinals.cbegin(),
?????????????????? ordinals.begin(), std::plus<>{});
?//或使用 std::plus<>()
??? print_ordinals(ordinals);
}
?
int main()
{
??? std::string hello("hello");
??? unary_transform_example(hello, "world");
?
??? std::vector<unsigned> ordinals;
??? std::copy(hello.cbegin(), hello.cend(), std::back_inserter(ordinals));
??? binary_transform_example(std::move(ordinals));
}
輸出:
hello = "HELLO"
world = "WORLD"
ordinals:? 72? 69? 76? 76? 79
ordinals: 144 138 152 152 158
說明:std::quoted 是 C++14 中引入的 I/O 操作符,屬于 <iomanip> 庫的一部分。其主要目的是簡化使用流進行輸入輸出操作時對帶引號的字符串的處理。