C++ 算法 std::transform

一 定義

  • std::transform應用給定的函數到範圍並存儲結果於另一範圍。
  • 定義於< algorithm >
template< class InputIt, class OutputIt, class UnaryOperation >
OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first,
                    UnaryOperation unary_op );(1)(C++20)
template< class InputIt, class OutputIt, class UnaryOperation >
constexpr OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first,
                              UnaryOperation unary_op );(1)(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 );(2)(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 );(3)(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 );(3)(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 );(4)(C++17)

二 Demo

  • Demo中輔助函數如下:
int plus1(int a) {
  return a + 10;
}

int plus2(int a, int b) {
  return a + b;
}
  • transform Demo
// std::transform
if (1) {
  std::list<int> l(10);
  std::vector<int> vc;
  fill(vc, 1, 9);

  print("before transform vc(src): ", vc);
  print("before transform list(dst): ", l);
  // 一元操作
  std::transform(vc.begin(), vc.end(), l.begin(), plus1);
  print("after transform vc(src): ", vc);
  print("after transform list(dst): ", l);
}
if (1) {
  std::list<int> l(10);
  std::vector<int> vc1;
  fill(vc1, 1, 9);
  std::vector<int> vc2;
  fill(vc2, 1, 9);

  print("before transform vc1(src): ", vc1);
  print("before transform vc2(src): ", vc2);
  print("before transform list(dst): ", l);
  // 二元操作
  std::transform(vc1.begin(), vc1.end(), vc2.begin(), l.begin(), plus2);
  print("after transform vc1(src): ", vc1);
  print("after transform vc2(src): ", vc2);
  print("after transform list(dst): ", l);
}
  • 結果
before transform vc(src): 1 2 3 4 5 6 7 8 9
before transform list(dst): 0 0 0 0 0 0 0 0 0 0
after transform vc(src): 1 2 3 4 5 6 7 8 9
after transform list(dst): 11 12 13 14 15 16 17 18 19 0

before transform vc1(src): 1 2 3 4 5 6 7 8 9
before transform vc2(src): 1 2 3 4 5 6 7 8 9
before transform list(dst): 0 0 0 0 0 0 0 0 0 0
after transform vc1(src): 1 2 3 4 5 6 7 8 9
after transform vc2(src): 1 2 3 4 5 6 7 8 9
after transform list(dst): 2 4 6 8 10 12 14 16 18 0

三 參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章