Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Build a generic `map` like function in cpp

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What’s the correct way?

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading