向量运算符[]和at()有什么区别 [英] What is the difference between the vector operator [] and at()

查看:170
本文介绍了向量运算符[]和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"

据我了解,向量[] operatorat方法之间的区别在于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.

两种解决方案:

  1. 由于MyVector是指针,因此需要取消引用该指针 首先找回vector.

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

(*MyVector)[i]

  • 较少使用:使用operator关键字:

  • Less used: Use the operator keyword:

    MyVector->operator[](i)
    

  • 这篇关于向量运算符[]和at()有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆