Converting an Array to a Vector in C++
For converting the elements stored in an array to a std::vector in C++, we can use the range constructor of std::vector that takes two iterators, one to the beginning and one to the end of the array.
Syntax to Convert Array to a Vector in C++
vector<type> vectorName(arrayName, arrayName + arraySize);
Here,
type
is the data type of the elements in the array and the vector.vectorName
is the name of the vector.arrayName
is the name of the array we want to convert to a vector.arraySize
is the number of elements in the array.
C++ Program to Convert an Array to a Vector
The below program demonstrates how we can convert an array to a vector in C++.
// C++ program to illustrate how to convert an array to a
// vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Array
int arr[] = { 10, 20, 30, 40, 50, 60 };
int n = sizeof(arr) / sizeof(arr[0]);
// Print the array
cout << "Array: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
// Convert array to vector
vector<int> vec(arr, arr + n);
// Print the vector
cout << "Vector: ";
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
cout << endl;
return 0;
}
Output
Array: 10 20 30 40 50 60 Vector: 10 20 30 40 50 60
Time Complexity: O(N), where n is the number of elements in the array.
Auxiliary Space: O(N)
How to Convert an Array to a Vector in C++?
In C++, arrays are fixed-size data structures that store elements of the same type. On the other hand, vectors are dynamic arrays that can grow and shrink in size as needed. In this article, we will learn how to convert an array to a vector in C++.
Example:
Input: myArray = {10,20,30,40,50,60} Output: myVector = {10,20,30,40,50,60}