
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
using namespace std; | |
int main() | |
{ | |
//Declare an integer array | |
vector<int> myarray; | |
//Now you have 10 items and wanna put them to your array | |
//Using the push_back function to add your content. | |
for (int i = 0; i < 10; i++) | |
{ | |
myarray.push_back(i); | |
} | |
for (int number : myarray) | |
cout << number << " "; | |
cout << endl; | |
//Now I just want 5 items in my array, just resizing that array | |
myarray.resize(5); | |
for (int number : myarray) | |
cout << number << " "; | |
cout << endl; | |
//After that, I will add 10 items to that array with the default values are 20. | |
//It means you have 5 items in your array, and add 10 more items. So 5 + 10 = 15. | |
//Put that number in the first section of the resize function. | |
myarray.resize(15, 20); | |
for (int number : myarray) | |
cout << number << " "; | |
cout << endl; | |
//Now I need more items, it's about 10 items. Just resizing that array again. | |
myarray.resize(25); | |
for (int number : myarray) | |
cout << number << " "; | |
cout << endl; | |
system("pause"); | |
return 0; | |
} |
No comments:
Post a Comment