为什么这些向量不相等? [英] Why aren't these vectors equal?

查看:51
本文介绍了为什么这些向量不相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个向量,另一个用 push_back 填充,另一个用索引填充.我希望这些是平等的,但事实并非如此.有人能解释一下这是为什么吗?

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;
}

推荐答案

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).

您不能使用 operator[] 来填充向量,因为它返回对底层对象的引用,在您的情况下,它只是一堆位.

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.

你应该使用 push_back() 或者只是 resize 你的向量.使用后者:-

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;

这篇关于为什么这些向量不相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆