我创建了两个向量,并用push_back填充了另一个向量,并用索引填充了另一个向量。我希望这些是平等的,但事实并非如此。有人可以解释一下为什么吗?
#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;
这可能是未定义的行为(尽管不确定是否取决于实现)。
您不能使用operator[]
填充向量,因为它会将参考返回给基础对象,在您的情况下,该对象不过是一堆比特而已。
您应该使用push_back()
OR或仅使用resize
向量。
vector<int> v1;
v1.resize(3);
v1[0] = 0;
v1[1] = 1;
v1[2] = 2;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句