【发布时间】:2020-07-28 06:28:21
【问题描述】:
vector <int> * v = new vector <int>;
v -> push_back (1);
cout << v[0]<< endl; // error
为什么我不能访问第一个元素?我收到此错误
错误:'operator
【问题讨论】:
vector <int> * v = new vector <int>;
v -> push_back (1);
cout << v[0]<< endl; // error
为什么我不能访问第一个元素?我收到此错误
错误:'operator
【问题讨论】:
为什么要分配vector 和new?使用向量的主要目的是避免必须使用 new。
vector<int> v;
v.push_back(1);
cout << v[0] << endl;
如果出于某种奇怪的原因你决定你真的必须使用指针,那么你可以这样做
vector<int>* v = new vector<int>;
v->push_back(1);
cout << (*v)[0] << endl;
但实际上,用new 分配向量没有什么意义。
也许您在尝试 C++ 之前是一名 Java 程序员?如果是这样,那么不要尝试以 Java 风格编写 C++,它们是非常不同的语言。如果你这样做,你会陷入可怕的混乱。
【讨论】:
因为v 是指向向量的指针,而不是引用或向量本身。因此v[0] 给你的不是你所期望的。它为您提供矢量对象本身。没有定义流输出operator<<。您必须使用(*v)[0]。
【讨论】:
您不太可能需要像这样动态分配vector,但如果您确实有一个指向向量的指针:
vector<int>* v = new vector<int>;
那么调用成员函数的正确语法是:
// dereferencing the pointer and then using the member functions
(*v).push_back(1);
cout << (*v)[0] << endl;
或
// using -> with the correct names of the member functions
v->push_back(1);
cout << v->operator[](0) << endl;
【讨论】: