store array in vector
To store an array in a vector in C++, you can follow these steps:
- Include the necessary header file: Start by including the
<vector>
header file, which provides the vector class template.
cpp
#include <vector>
- Declare and initialize an array: Declare and initialize your array with the desired values.
cpp
int arr[] = {1, 2, 3, 4, 5};
- Create a vector object: Create a vector object of the desired type. In this case, we'll use an
int
vector.
cpp
std::vector<int> vec;
- Copy the array elements to the vector: Use the
assign
function to copy the elements from the array to the vector.
cpp
vec.assign(arr, arr + sizeof(arr) / sizeof(arr[0]));
In this line of code, sizeof(arr)
returns the total size of the array, and sizeof(arr[0])
returns the size of a single element in the array. Dividing the total size by the size of a single element gives us the number of elements in the array. The assign
function copies the elements from the array to the vector.
- Access the vector elements: You can now access the elements of the vector using the same syntax as an array. For example, to access the first element:
cpp
int firstElement = vec[0];
Note that the index of the vector starts from 0, just like in arrays.
And that's it! You have now stored an array in a vector in C++.
Let me know if you have any further questions.