vector::push_back vs vector::operator[]

后端 未结 2 939
迷失自我
迷失自我 2020-12-15 02:19

Below in c++ program,

include
#include
using namespace std;

int main()
{
     vector numbers;

    n         


        
2条回答
  •  感情败类
    2020-12-15 02:46

    push_back creates a new element on the back with the value specified. operator[] requires the element to be there; it just accesses it. The reason [5] doesn't work is because you have 5 elements, so your indices range from 0 to 4.

    Generally, when adding new elements, push_back is preferred over resize, followed by operator[]. Only one can be used for reading, though, and operator[] is also needed to maintain normal array syntax.

提交回复
热议问题