c++qtc++17qvector

How to convert a QVector to another with different types


How do I write a simple function (in C++ 17) that can get one QVector of any type, and returns a new one with converted values of any other type. For example:

auto my_function(auto in, auto f) 
{
    // ... body of function
}

// Usage:

auto my_lambda = [] (int x) { return QString::number(x); }
QVector<int> in_vector = {1,2,3};
QVector<QString> res = my_func(in_vector, my_lambda);

Solution

  • Ok, let it be something like this

    template<typename F>
    auto my_map(const auto &data, F f)
    {
        using ReturnType = std::invoke_result_t<F, decltype(data.at(0))>;
        QVector<ReturnType> res(data.size());
        std::transform(data.begin(), data.end(), res.begin(), f);
        return res;
    }
    

    It works for non-empty vectors quite well.

    UPD: Yet another working variant:

    auto my_map(const auto &data, auto f)
    {
        using ReturnType = decltype(f(data.at(0)));
        QVector<ReturnType> res(data.size());
        std::transform(data.begin(), data.end(), res.begin(), f);
        return res;
    }