Initializing a Vector from an Array
Create and initialize a vector from an array using the following code:
// Initializing a vector from an array
int a[] = {11, 22, 33};
int n = sizeof(a) / sizeof(a[0]); // number of elements in the array
vector<int> v1(a, a + n); // create and initialize the vector from the array
// Print the vector
cout << "The elements of the second vector are: ";
for (int i : v1)
{
cout << i << " ";
}
This will create an array a
and initialize it with three elements. We can then calculate the number of elements in this array and create a vector v1
and initialize it with the elements of the array. We can then print the elements of this vector using the for
loop.