Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ copy map to vector with std::move

I'm relativly new to C++ and this might be a foolish question but I'm trying to understand rValue and lValue references at the moment and this came to my mind:

Let's say we have a map (which comes from a database or whatever) and we want to copy all values of it to a vector.

void insertItems(std::vector<std::string>& v)
{
    std::map<int, std::string> names = loadFromDb();

    for (auto& kv : names )
    {
        v.push_back(std::move(kv.second));
    }
}

Is it right to use std::move here? std::string provides an move constructor and (maybe not for string but for larger objects) the move constructor is much faster than the copy constructor. Also we know that we do not use the items of the map somewhere else and they go out of scope as soon as we leave the function. So is my presumption right?

I can't see a contradiction in my thoughts but it's a complicated topic and I'm afraid to miss something. P.S.: I think the question name is not the best. If you have a better one feel free to edit it.

like image 822
Cilenco Avatar asked Oct 27 '25 10:10

Cilenco


2 Answers

Is it right to use std::move here?

If you are sure that you won't access the moved values in the future, yes.


You might also want to use std::vector::reserve to preallocate the required space in v.

v.reserve(v.size() + names.size());
like image 61
Vittorio Romeo Avatar answered Oct 28 '25 22:10

Vittorio Romeo


Is it right to use std::move here?

Yeah. The code looks fine.

like image 39
emlai Avatar answered Oct 28 '25 23:10

emlai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!