Daily Dose C++: Vector Copy

Note

Been keeping busy, missed out on a month of C++ Dosing.

  • NVIDIA GTC a few weeks ago
  • Going through the CPP Con talks
  • Fast.AI video tutorial/book read
  • Learning CMake and GUI Frameworks. (going with GTK)

Maybe I should just reduce the scope of the daily dosage. But I digress.

Taking a Data structures in C++ class for review/fun. Ran into a problem where we wanted to copy a vector object into a new one.

The Dose

Iterate and Copy

// Lambda to do the copy:
auto vectorCopy = [](std::vector<int> vIn) -> std::vector<int>
{
    std::vector<int> vOut;
    for (auto v: vIn)
        vOut.emplace_back(v);
    return vOut;
};

// Usage:
std::vector<int> copyTo = vectorCopy(copyFrom);

Easy to implement, but thought, there has to be a better way!

std::copy

std::copy(copyFrom.begin(), copyFrom.end(), back_inserter(copyTo));

Thought this was straightforward, but wasn't as easy as I thought.
You need to use the back_inserter as the third argument.

Why? I'm not too sure myself. What other use cases are there?

Copy During Initialization

std::vector<int> copyFrom = {1, 2};
std::vector<int> copyTo(copyFrom);

Now this is pretty elegant. Pass in another vector object and it will create the copy during initialization. This is the one we ultimately went with.


You'll only receive email when Wron publishes a new post

More fromĀ Wron