How to create a dynamic array of integers in C++


This is an easy way to create a dynamic array of integers, strings, or another object in C++.

Using the Standard Template Library in C++11. Using the vector class declares your array.
#include <vector>

vector<int> myarray;
vector<string> mystringarray;

Please follow my example to understand how to create a dynamic arrays in C++

I will create 10 items and add some contents in that array by using the push_back function.

But I do not need 10 items, just 5 items are enough. So I use the resize() function to change the size of array.

After that, I need 10 more items and their values are 20. So 5 items in my array plus 10 items, it will be 15 items.

myarray.resize(15, 20); the first section is for your number of items in your array, and the second section is for their values of the 10 items later.

Finally, I need more items, it's about 10 items. Just resizing one more time. But I do not want put values for them. So their values will be 0.

How to create a dynamic array of integers in C++

No comments:

Post a Comment