[英]How can I push_back data in a vector via a vector::pointer?
I 'd like to use a vector::pointer so as to push_back data in it.. 我想使用vector :: pointer以便在其中push_back数据。
int num;
vector<int> v;
vector<int>::pointer ptr;
ptr = &v[0];
ptr->push_back(num); // fail
ptr.push_back(num); // fail
ptr.push_back(&num); // fail
*ptr.push_back(num); // fail
nothing appears to work.. any ideas would be appreciated.. 没有任何效果。.任何想法将不胜感激..
You are misunderstanding what vector::pointer is. 您误解了vector :: pointer是什么。 That's a type for a pointer to an element in the vector, not a pointer to a vector itself.
这是指向向量中元素的指针的类型,而不是向量本身的指针。
That aside, it's not clear to me why you would want to do this since .
除此之外,我不清楚您为什么以后要这么做
.
notation works just fine and saves you the pointer dereference on each access. 记法工作得很好,并且可以节省每次访问时指针的取消引用。 If you find yourself typing in
vector<int> *vecPtr = new vector<int>;
如果您发现自己输入
vector<int> *vecPtr = new vector<int>;
, take a deep breath and ask why you cannot use RAII . ,深吸一口气,问为什么你不能使用RAII 。
You can't. 你不能 You need to use the original vector object.
您需要使用原始矢量对象。
If you'd like to have a pointer to a vector, you can do the following: 如果您想要一个指向矢量的指针,则可以执行以下操作:
vector<int> v;
vector<int> *pointer = &v;
v.push_back(4);
pointer->push_back(3);
As a comment, the type of vector<int>::pointer
in your code should be int *
. 作为注释,代码中
vector<int>::pointer
的类型应为int *
。
in this case ptr
is an int*
not a pointer to a vector<int>
so it cannot perform vector operations. 在这种情况下,
ptr
是int*
而不是指向vector<int>
的指针,因此它无法执行向量运算。 When you make the assignment: 进行作业时:
ptr = &v[0];
you're assigning the pointer to the address containing the integer at v[0], not assigning a reference to the vector. 您正在将指针分配给包含v [0]处的整数的地址,而不是对向量的引用。 To do what you want, you need to do the following:
要执行您想要的操作,您需要执行以下操作:
int num;
vector<int> v;
vector<int>* ptr;
ptr = &v;
ptr->push_back(num);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.