add an element to an empty vector in c++: why push

2020-05-09 18:43发布

问题:

Some years ago I had an introductory course to c++ at my university. However, I mainly used functional languages such as R or Matlab. Now I started again to learn c++. I was reading about vectors and run in the following:

    #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;
    } 

If I use default initialization for test1, why do I have to use puch_back? Wouldn't it be "smarter" to use the [] operator and automatically insert the element? Why is this forbidden in c++?

回答1:

std::vector's operator[] is designed to have the same semantics as it does for plain arrays. That is, it gives you access to an existing element with a certain index. An empty vector has no existing elements, so you have to add them in. push_back is one way of doing that. It has the effect of appending a new element to the back of a vector, increasing its number of elements by 1.



标签: c++ vector