Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

What is the best way to copy a 2d vector

Say i have the following scenario:

std::vector<std::vector<double>> v(6, std::vector<double>(6, 0.0));
std::vector<std::vector<double>> y;

for (const std::vector<double> &p : v) {
    y.push_back(p);
}

This is taking a deep copy of the v into y. Is there a way to do this with std::copy on a 2D vector.

std::copy(v.begin(), v.end(), y.begin())

will not work. For bonus points can this be extended to an ND vector case? This seems important to avoid the following loops which would be N deep:

...
for (const std::vector<std::vector<<double>> &p : v) {
    for (const std::vector<double> &q : p) {
        ...

I know that performance wise there is no difference as this is how std::copy is implemented. Just wondering in terms of code compactness.

Upvotes: 7

Views: 20430

Answers (2)

vsoftco
vsoftco

Reputation: 56557

In case y has no memory pre-allocated, a simple copy with std::begin(y) will cause undefined behaviour. For 2D-vectors, you can use std::copy with a back_inserter from <iterator>, like

std::copy(v.begin(), v.end(), back_inserter(y));

Upvotes: 5

billz
billz

Reputation: 45410

The good practice to copy a STL container to another is : copy construct. Code should be faster and exception safe.

For example:

auto y(v);

If y is already created, use vector::insert

y.insert(y.end(), v.begin(), v.end());

or

y = v;

Upvotes: 18

Related Questions