vector::push_back vs vector::operator[]

流过昼夜 提交于 2019-11-29 00:43:31

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!