I've created two vectors and filled the other one with push_back and the other one with indices. I would expect these to be equal but ther aren't. Can someone explain me why is this?
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> v0;
v0.push_back(0);
v0.push_back(1);
v0.push_back(2);
vector<int> v1;
v1.reserve(3);
v1[0] = 0;
v1[1] = 1;
v1[2] = 2;
if (v0 != v1) {
cout << "why aren't they equal?" << endl;
}
return 0;
}
In both cases, when vectors have either different directions, or different lengths, they are not equal. Likewise, if both direction and length are different they are not equal. Two vectors are equal only when both directions and lengths are the same.
A vector is said to be an equal vector to another vector if they both have the same magnitude and the same direction. In simple words, we can say that two or more vectors are said to be equal vectors if their length is the same and they all point in the same direction.
Equal VectorsTwo or more vectors are said to be equal when their magnitude is equal and also their direction is the same. The two vectors shown above, are equal vectors as they have both direction and magnitude equal.
Two vectors are considered to be equal only if they have the same magnitude and direction. Vectors v and w are the same since they have the same magnitude and direction. Vectors v and w are not the same because they have different directions.
vector<int> v1;
v1.reserve(3);
v1[0] = 0;
v1[1] = 1;
v1[2] = 2;
This is probably an undefined behavior ( although not sure if it's implementation dependent).
You cannot use operator[]
for filling up the vector as it's returning the reference to the underlying object which in your case is nothing other than bunch of bits.
You should either use push_back()
OR just resize
your vector.Using latter:-
vector<int> v1;
v1.resize(3);
v1[0] = 0;
v1[1] = 1;
v1[2] = 2;
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