一 std::transfrom
定义于头文件 <algorithm>
template< class InputIt, class OutputIt, class UnaryOperation >
OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first,
UnaryOperation unary_op ); (C++20 前)
template< class InputIt, class OutputIt, class UnaryOperation >
constexpr OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first,
UnaryOperation unary_op ); (C++20 起)
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class UnaryOperation >
ForwardIt2 transform( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 d_first, UnaryOperation unary_op ); (C++17 起)
template< class InputIt1, class InputIt2, class OutputIt, class BinaryOperation >
OutputIt transform( InputIt1 first1, InputIt1 last1, InputIt2 first2,
OutputIt d_first, BinaryOperation binary_op ); (C++20 前)
template< class InputIt1, class InputIt2, class OutputIt, class BinaryOperation >
constexpr OutputIt transform( InputIt1 first1, InputIt1 last1, InputIt2 first2,
OutputIt d_first, BinaryOperation binary_op ); (C++20 起)
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2,
class ForwardIt3, class BinaryOperation >
ForwardIt3 transform( ExecutionPolicy&& policy, ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 first2, ForwardIt3 d_first, BinaryOperation binary_op );
(C++17 起)
std::transform 应用给定的函数到范围并存储结果于始于 d_first 的另一范围
二 例子
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <iterator>
#include <functional>
std::map<int, int> mp{
{1, 11},
{2, 22},
{3, 33},
{4, 44}
};
int main() {
std::vector<int> vc;
std::transform(mp.begin(), mp.end(), std::back_inserter(vc),
std::bind(&std::map<int, int>::value_type::second, std::placeholders::_1));
for (auto i : vc) {
std::cout << i << std::endl; // output: 11 22 33 44
}
std::cin.get();
return 0;
}