Skip to content

Instantly share code, notes, and snippets.

@piyo7
Last active August 29, 2015 14:06
Show Gist options
  • Save piyo7/cf0aedbaf5f488087279 to your computer and use it in GitHub Desktop.
Save piyo7/cf0aedbaf5f488087279 to your computer and use it in GitHub Desktop.
変換先のstd::vectorを作って返すstd::transform ref: http://qiita.com/piyo7/items/c2f7a69e36b50313a074
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment