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.
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].
Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector.
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.
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;
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With