I was expected that with
v2 = v1
the content of v1 is copied into v2.
What I experience is that the content of v1 is not copied into v2 if the content of v1 was not initialized in constructor.
Just see the code:
#include <iostream>
#include <vector>
using namespace std;
int main (void) {
vector<int> v1; // if I use vector<int> v1(10,0); it just works fine
vector<int> v2;
v1.reserve(5);
v2.reserve(5);
for (int i = 0; i < 5; i++) v1[i] = i*i;
v2 = v1;
for (int i = 0; i < 5; i++) {
cout << "v1[" << i << "] = " << v1[i] << endl;
cout << "v2[" << i << "] = " << v2[i] << endl;
}
return 0;
}
The result of the execution is:
v1[0] = 0
v2[0] = 0
v1[1] = 1
v2[1] = 0
v1[2] = 4
v2[2] = 0
v1[3] = 9
v2[3] = 0
v1[4] = 16
v2[4] = 0
Why this strange behaviour?
Your expectation is correct. v2 = v1;
copies all the elements of v1
into v2
. The problem is that you are accessing your vectors out of bounds. This is undefined behaviour .
std::vector::reserve
does not increase their size. It simply allocates more storage for the size to grow into as needed. You need to call std::vector::resize
instead, initialize the vector to have the right size, or call push_back
in the loop.
Note that you should use the size()
member variable, the begin()
and end()
iterators, or a range-based for-loop to iterate over a vector. That will ensure you do not access out of bounds.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.