vector::push_back vs vector::operator[]

后端 未结 2 938
迷失自我
迷失自我 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.

    0 讨论(0)
  • 2020-12-15 02:47

    std::vector::operator[]: "access specified element"

    std::vector::push_back: "adds an element to the end"

    I'm so amazing at looking at c++ references. You should try it.

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