Whenever we declare a vector like:
vector<int> v;
Here, we do not specify the size of our vector. Whenever we just want to add an element we just push it into the vector using the v.push _ back(val)
function (where val is the value you want to push).
Suppose you haven't added any elements into the vector. Now, if you go on access any element position like v[0]
or v[7]
like one can when he declares an array, you will get a runtime error. Why? Because vectors are dynamic in nature. Since, you haven't declared any size or pushed any element it's size is zero. So no element exists right now.
But if you declare it using: