Why are these vectors not equal?

I created two vectors and populated another push_back and the other with indexes. I would expect them to be equal, but they will not. Can someone explain to me why this is?

#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; } 
+8
c ++ vector
source share
1 answer
 vector<int> v1; v1.reserve(3); v1[0] = 0; v1[1] = 1; v1[2] = 2; 

This is probably undefined behavior (although not sure if it is implementation dependent).

You cannot use operator[] to populate a vector, because it returns a reference to the underlying object, which in your case is nothing more than a bunch of bits.

You must either use push_back() OR just resize your vector. Using the latter: -

 vector<int> v1; v1.resize(3); v1[0] = 0; v1[1] = 1; v1[2] = 2; 
+8
source share

All Articles