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

后端 未结 1 1267
执笔经年
执笔经年 2021-01-24 02:33

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 rea

相关标签:
1条回答
  • 2021-01-24 02:49

    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.

    0 讨论(0)
提交回复
热议问题