9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

変換先のstd::vectorを作って返すstd::transform

Last updated at Posted at 2014-09-27

C++のstd::transformは、変換先のコンテナを呼び出し側で確保してイテレータ書く必要があるので、たいがいの場合に冗長。
関数型のmap関数のように、自動で変換先のstd::vectorを作って返すstd::transformが欲しかったので、下記のようなものを書いてみた。

# include <algorithm>
# include <iostream>
# include <type_traits>
# include <vector>

template <
  typename Input,   // 引数から推論されるので省略可
  typename Functor, // 引数から推論されるので省略可
  typename Output = typename std::result_of<Functor(Input)>::type
>
std::vector<Output> transform_copy(
  const std::vector<Input>& inputs,
  Functor func
) {
  std::vector<Output> outputs(inputs.size());
  std::transform(inputs.cbegin(), inputs.cend(), outputs.begin(), func);
  return outputs; // NRVOが効いてmoveされるはず
}

int main() {
  std::vector<int> vec = {1, 2, 3, 4, 5};
  for (auto element : transform_copy(vec, [](int i){ return i * i; })) {
    std::cout << element << ", "; // 1, 4, 9, 16, 25,
  }
  std::cout << std::endl;

  return 0;
}

実行結果:[Wandbox]三へ( へ՞ਊ ՞)へ ハッハッ

std::result_ofのおかげで、テンプレート引数書かなくて済むのがポイント。
C++11で導入された型操作ライブラリに入っている。
Standard library header - cppreference.com

9
9
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?