Home > Back-end >  Build a generic `map` like function in cpp
Build a generic `map` like function in cpp

Time:06-04

Consider

template <typename S, typename T, typename F>
vector<T> map(const vector<S> &ss, F f){
    vector<T> ts;
    ts.reserve(ss.size());
    std::transform(ss.begin(), ss.end(), std::back_inserter(ts), f);
    return ts;
}

int main(){
    vector<int> is = {...};
    vector<double> ts = map(is, [](int i){return 1.2*i;});
}

because the compiler 'couldn't deduce template parameter T'. Specifying map of type

template <typename S, typename T>
vector<T> map(const vector<S> &ss, std::function<T(S)> f)

also doesn't work, because it doesn't match lambdas.

What's the correct way?

CodePudding user response:

Something like this:

template <typename S, typename F>
auto map(const std::vector<S> &ss, F f) -> std::vector<std::decay_t<decltype(f(ss[0]))>>
{
    std::vector<std::decay_t<decltype(f(ss[0]))>> ts;
    ts.reserve(ss.size());
    std::transform(ss.begin(), ss.end(), std::back_inserter(ts), std::move(f));
    return ts;
}

I've opted for a trailing return type, to be able to use f and ss in decltype. You could just use auto return type, but explicitly specifying the type makes the function SFINAE-friendly.


Or, a slightly overengineered version with hottest C 20 features:

template <
    template <typename...> typename C = std::vector,
    typename S, typename F
>
[[nodiscard]] C<std::decay_t<std::indirect_result_t<F, std::ranges::iterator_t<S>>>>
map(S &&ss, F f)
{
    C<std::decay_t<std::indirect_result_t<F, std::ranges::iterator_t<S>>>> ts;
    ts.reserve(std::ranges::size(ss));
    std::ranges::transform(ss, std::back_inserter(ts), std::move(f));
    return ts;
}

CodePudding user response:

this works

  std::vector<double> ts = map<int, double>(is, [](int i) {return 1.2 * i; });
  • Related