Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 766
Fantastic Mr Fox Avatar asked Jul 30 '14 00:07

Fantastic Mr Fox


People also ask

How do I print a 2D vector size?

Print “the 2D vector is:”. for (int i = 0; i < v. size(); i++) for (int j = 0; j < v[i]. size(); j++) print the value of 2D vector v[i][j].

Does Push_back make a copy?

Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector.

What is a vector copy?

Copy enables you to: define a vector of operands, copy the values or bit status of each operand within that vector, write those values or status into a corresponding vector of operands of the same length.


2 Answers

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;
like image 62
billz Avatar answered Sep 28 '22 15:09

billz


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));
like image 29
vsoftco Avatar answered Sep 28 '22 17:09

vsoftco