Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't these vectors equal?

Tags:

c++

vector

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;
}
like image 591
aks Avatar asked Dec 14 '14 18:12

aks


People also ask

Why are the two vectors not equal?

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.

How do you know if vectors are equal?

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.

Are these two vectors equal?

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.

Can vectors be the same?

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.


1 Answers

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;
like image 133
ravi Avatar answered Sep 18 '22 07:09

ravi