在 C++ 中将元素添加到空向量:为什么 push.back 有效而 [] 无效

add an element to an empty vector in c++: why push.back works and [] not

本文关键字:back push 为什么 有效 无效 向量 C++ 元素 添加      更新时间:2023-10-16

几年前,我在大学里上了一门 c++ 入门课程。但是,我主要使用函数式语言,如R或Matlab。现在我又开始学习c++。我正在阅读有关向量的信息,并在以下内容中运行:

    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <vector>
    int main()
    {      
      std::vector<int> test1;
  std::vector<int> test2(2);
  // works perfectly as expected:
  test2[0] = 1;
  test2[1] = 2;
  // this would give an error
  //test1[0] = 1;
  //instead I have to write
  test1.push_back(1);
      return 0;
    } 

如果我对 test1 使用默认初始化,为什么我必须使用 puch_back?使用 [] 运算符并自动插入元素不是"更聪明"吗?为什么这在 C++ 中是被禁止的?

std::vectoroperator[]被设计为具有与普通数组相同的语义。也就是说,它使您可以访问具有特定索引的现有元素。空向量没有现有元素,因此您必须添加它们。 push_back是做到这一点的一种方式。它具有将新元素附加到向量背面的效果,将其元素数增加 1。