How to Assign a std::vector Using a C-Style Array?
Last Updated :
29 Jan, 2024
In C++, std::vector are the dynamic array containers that replace the plain old C-style arrays and it is very common to assign the values of those C-Style to std::vector. In this article, we will learn how to assign a std::vector using C-style arrays.
For Example,
Input:
arr[] = {1, 5, 7, 9, 8}
vector<int> vec = {}
Output:
vec = {1, 5, 7, 9, 8}
Assign a C-Style Array to std::vector
To assign a C-Style Array to std::vector, we can use the std::vector::assign() function that replaces the old values of the vector and assigns them the new values. We need to pass the starting and ending address of the array to the function as the argument.
C++ Program to Assign Vector using C-Style Array
C++
#include <iostream>
#include <vector>
int main()
{
int cArray[] = { 1, 2, 3, 4, 5 };
std::vector< int > myVector;
int size = sizeof (cArray) / sizeof (cArray[0]);
myVector.assign(cArray, cArray + size);
std::cout << "Vector elements: " ;
for ( int i : myVector) {
std::cout << i << " " ;
}
std::cout << std::endl;
return 0;
}
|
Output
Vector elements: 1 2 3 4 5
If we want to insert elements after the currently present elements in the vector, we can use the std::vector::insert() function.
Share your thoughts in the comments
Please Login to comment...