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);
}

It makes a deep copy vin y. Is there any way to do this using std::copyin vector 2D.

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

will not work. For bonus points, can this be expanded to a vector ND? This seems important to avoid the following loops that would be Ndeep:

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

I know that performance is reasonable, there is no difference since it is implemented std::copy. Just interesting from the point of view of compactness of the code.

+4
source share
2 answers

STL : copy construct. .

:

auto y(v);

y , vector::insert

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

y = v;
+9

y , std::begin(y) undefined. 2D- std::copy back_inserter <iterator>,

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

All Articles