Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating elements in C++ vector after declaration

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.
like image 344
Shamim Hafiz - MSFT Avatar asked May 07 '11 17:05

Shamim Hafiz - MSFT


People also ask

Can you resize a vector after declaring it?

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.

How do I allocate memory with std::vector?

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.

Does std::vector assign allocate?

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.


2 Answers

You simply need to resize the vector before adding the new values:

v1.resize(20);
like image 156
Aaron Avatar answered Oct 12 '22 22:10

Aaron


You could use resize like this:

v1.resize(20);
like image 43
Bart Avatar answered Oct 12 '22 22:10

Bart