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

落爺英雄遲暮 提交于 2020-01-15 09:48:47

问题


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:

  1. Since MyVector is a pointer, you need to dereference the pointer first to get back the vector.

    (*MyVector)[i]
    
  2. 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 ith 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!