Open In App

How to Assign a std::vector Using a C-Style Array?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to assign the vector using a c-style array
#include <iostream>
#include <vector>
  
int main()
{
    // Define a C-style array
    int cArray[] = { 1, 2, 3, 4, 5 };
  
    // Create a vector to store the values from the C-style
    // array
    std::vector<int> myVector;
  
    // Calculate the size of the C-style array
    int size = sizeof(cArray) / sizeof(cArray[0]);
  
    // Use the assign() function to copy values from the
    // C-style array to the vector
    myVector.assign(cArray, cArray + size);
  
    // Display the contents of the vector
    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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads