Please refer to the code and comments below:
vector<int> v1(10);
cin>>v1[0]; // allowed
cin>>v1[1]; // allowed
// now I want v1 to hold 20 elements so the following is possible:
cin>>v1[15]>>v[19]; // how to resize the v1 so index 10 to 19 is available.
Vectors are sequence containers which represent arrays which can change in size. Thus, we need not specify its length at the time of declaration and can change it later in the program.
An std::vector manages its own memory. You can use the reserve() and resize() methods to have it allocate enough memory to fit a given amount of items: std::vector<int> vec1; vec1. reserve(30); // Allocate space for 30 items, but vec1 is still empty.
As mentioned above, std::vector is a templated class that represents dynamic arrays. std::vector typically allocates memory on the heap (unless you override this behavior with your own allocator). The std::vector class abstracts memory management, as it grows and shrinks automatically if elements are added or removed.
You simply need to resize the vector before adding the new values:
v1.resize(20);
You could use resize like this:
v1.resize(20);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With