为什么向量中的第-1个索引始终为0?

有人能说为什么这段代码打印 0 吗?我认为它会显示一些例外情况。

int main()
{
    std::vector<int> v;
    v.push_back(8);
    cout << v[-1];
}

回答

为什么向量中的第 -1 个索引始终为 0?

它不是。程序的行为未定义。

我认为它会显示一些例外情况。

你的期望被误导了。std:vector::operator[]当索引越界时,不能保证抛出异常。

std:vector::at 确实如您所愿。

  • It should be noted that the MSVC standard library have an extension that throws out of bounds exceptions even for `operator[]`, at least in debug builds.

以上是为什么向量中的第-1个索引始终为0?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>