mardi 13 juillet 2021

Filling vector with emplace_back vs. std::transform

It's oversimplified code with a simple vector and class.

class OutputClass
{
public:
OutputClass(int x, int y);
};

std::vector<OutputClass> Convert(std::vector<int> const &input)
{
    std::vector<OutputClass> res;
    res.reserve(input.size());
    //either (1)
    for (auto const &in : input)
        res.emplace_back(in, in*in);
    return res;
    //or something like (2)
    std::transform(input.begin(), 
                   input.end(), 
                   std::back_inserter(res), 
                   [](InputClass const &in){return OutputClass(in, in*in);});
    return res;
}  

Is there a difference in performance between those two options? Static analyzers often have a rule for replacing all raw loops with algorithms, but in this case, it seems to me that looping with emplace_back would be more efficient, as we don't need either copy or move. Or I'm wrong and they are equal in terms of performance and (2) is preferable in terms of good style and readability?

Aucun commentaire:

Enregistrer un commentaire