C++ variable sized arrays
Today we are going to dig in arrays. Array is a built in abstract data type in C programming. You can conceptualize it as a collection of similar elements. The element number of an array must be initialized when it’s declared. What if you wanted to store more elements in arrays after you’ve already declared it? C++ vector class template stands for this concept. Using vector arrays you can resize it dynamically.
Task.
In nested loop, storing arrays as a element of an array we can solve this problem simply.
main_array = {
{1, 5, 4}, //this is 0 indexed element_array of main_array
{1, 2, 8, 9, 3}//this is 1 indexed element_array of main_array
}
Let’s implement the main_array storing n sequence of k length arrays. Consider the explanation comments in code below. Push_back is a method for vector class which stores its argument as a last element of a vector array.
int n,q;
cin>>n>>q; //storing the main_array length and query number.//this is the declaration of integer array containing array.
vector<vector<int>> main_array;
for(int i=0; i<n; i++) {
int k;
cin>>k;//getting length of element_array
vector<int> element_array;
for(j=0; j<k; j++) {
//storing integers as a last element of element_array
int c;
cin>>c;
element_array.push_back(c);
}
//storing element_array in main_array as a last element
main_array.push_back(element_array);
}
When the queries come, we just return second query indexed element of an array from first query indexed main_array.
for(i=0; i<q; i++) {
int n,k;
cin>>n>>k;
cout<<main_array[n][k]<<endl;
}
Finally our console program looks like below.
#include <vector> //including vector class header
#include <iostream>
using namespace std;int main() {
int n, q, i, j;
cin>>n>>q;
vector<vector<int>> main_array;
for(i=0; i<n; i++) {
int k;
cin>>k;
vector<int> element_array;
for(j=0; j<k; j++) {
int c;
cin>>c;
element_array.push_back(c);
}
main_array.push_back(element_array);
}
for(i=0; i<q; i++) {
int n,k;
cin>>n>>k;
cout<<main_array[n][k]<<endl;
}
return 0;
}
Hope you enjoyed it. Create your world using vectors!