问题
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"
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?
EDIT:
Whole code here
#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");
}
回答1:
The MyVector
is a pointer to a vector, not a vector.
Two solutions:
Since
MyVector
is a pointer, you need to dereference the pointer first to get back thevector
.(*MyVector)[i]
Less used: Use the
operator
keyword:MyVector->operator[](i)
回答2:
The problem is that you've declared a pointer to a vector. In the second expression, you are effectively treating MyVector
as an array in which you are trying to access the i
th element of type std::vector<int*>
(which I assume does not exist).
来源:https://stackoverflow.com/questions/53645285/what-is-the-difference-between-the-vector-operator-and-at