向量运算符 [] 和 at() 有什么区别

What is the difference between the vector operator [] and at()

我正在摆弄指向指针向量的指针

std::vector<int*>* MyVector;

我尝试使用这两种方法访问:

MyVector->at(i);    //This works
MyVector[i]         //This says "Expression must be a pointer to a complete object type"

据我了解,vectors [] operatorat 方法的区别在于 at 方法会进行额外的边界检查,所以我的问题是为什么 at 方法能够成功访问元素而 [] operator 没有?

编辑:

完整代码在这里

#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 视为一个数组,您试图在其中访问 std::vector<int*> 类型的第 i 个元素(我假设它不存在)。

MyVector 是指向矢量 的 指针,而不是 矢量

两种解决方案:

  1. 由于MyVector是一个指针,所以需要解引用指针 首先取回 vector.

    (*MyVector)[i]
    
  2. 较少使用:使用operator关键字:

    MyVector->operator[](i)