向量运算符[]和at()有什么区别 [英] What is the difference between the vector operator [] and at()
问题描述
我正在弄乱一个指向指针向量的指针
I'm messing around with a pointer to a vector of pointers
std::vector<int*>* MyVector;
我尝试使用以下两种方法进行访问:
Which I try to access using these 2 methods:
MyVector->at(i); //This works
MyVector[i] //This says "Expression must be a pointer to a complete object type"
据我了解,向量[] operator
和at
方法之间的区别在于at方法会执行其他边界检查,所以我的问题是为什么at方法会成功访问元素,而[] operator
会不是吗?
To my understanding, the difference between a vectors [] operator
and at
method is that the at method does additional boundary checks, so my question is why does the at method succeed in accessing the element whereas the [] operator
does not?
此处是整个代码
#include <vector>
#include <iostream>
std::vector<int*>* MyVector;
int main()
{
MyVector = new std::vector<int*>;
MyVector->push_back(new int(5));
for (unsigned int i = 0; i < MyVector->size(); i++)
{
delete MyVector->at(i); //This works
delete MyVector[i]; //This says "Expression must be a pointer to a complete object type
}
system("pause");
}
推荐答案
MyVector
是向量的指针,而不是向量 .
The MyVector
is a pointer to a vector, not a vector.
两种解决方案:
-
由于
MyVector
是指针,因此需要取消引用该指针 首先找回vector
.
Since
MyVector
is a pointer, you need to dereference the pointer first to get back thevector
.
(*MyVector)[i]
较少使用:使用operator
关键字:
Less used: Use the operator
keyword:
MyVector->operator[](i)
这篇关于向量运算符[]和at()有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!