C++ Programming : Array and Vector

This tutorial will show you how to use array and vector in C++. We assume that you have already done the previous tutorial.


Array

The general array declaration format is :

 type_array_data_with_pointer name_of_array = new type_array_data[number_of_array_allocation];

This code will show how to initialize an array and allocate array with for loop. In your main function :

// main function
int main(int argc, char** argv)
{
int key;
// array declaration
int* data = new int[10];
// use for loop to fill the array one by one
for (int i=0; i<10; i++)
{
// fill the i-th data with a value
data[i] = i;
// show the value inside i-th data
cout << “value inside “ << i << “-th data is “ << data[i] << “\n”;
}
cin >> key;
return 0;
}

The result is :

array


Vector

The general vector declaration format is :

// this declaration will create dynamic vector

vector<type_vector_data> name_of_vector;

// this declaration will create static vector

vector<type_vector_data> name_of_vector(number_of_vector_allocation);

This code will show how to initialize dynamic vector and allocate vector with for loop. In your main function :

// main function
int main(int argc, char** argv)
{
int key;
// dynamic vector declaration
vector<int> data;
// use for loop to fill the vector one by one
for (int i=0; i<10; i++)
{
// fill the i-th data with a value
data.push_back(i);
// show the value inside i-th data
cout << “value inside “ << i << “-th data is ” << data[i] << “\n”;
}
cin >> key;
return 0;
}

The result is :

array

This code will show how to initialize static vector and allocate vector with for loop. In your main function :

// main function
int main(int argc, char** argv)
{
int key;
// static vector declaration
vector<int> data(10);
// use for loop to fill the vector one by one
for (int i=0; i<10; i++)
{
// fill the i-th data with a value
// you can use this
data.at(i) = i;
// or this
data[i] = i;
// show the value inside i-th data
cout << “value inside “ << i << “-th data is “ << data[i] << “\n”;
}
cin >> key;
return 0;
}

The result is :

array