Below in c++
program,
include
#include
using namespace std;
int main()
{
vector numbers;
n
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.