In: Computer Science
C++ Write a toVector function that takes in a C-style pointer of any type and a size (int) and returns a vector of the same size containing a copy of the elements in the input array. You may assume that the array elements have a valid copy constructor. Please explain every line of code to me
Code:
#include<iostream>
#include<vector>
using namespace std;
//function toVector definition.
//Since the array is int array the return type should be vector<int>
vector<int> toVector( int *arr, int n)
{
//declare a new int vector xvec
vector<int> xvec;
//using for loop from 0 to n
for(int i=0; i<n; i++)
{
//add elements of array to xvec vector using push_back()
xvec.push_back(*arr);
//increment the var1++ so that it goes to next address of elements
arr++;
}
//return xvec
return(xvec);
}
int main()
{
//initialize an array
int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int n = sizeof(arr)/sizeof(arr[0]);
//store the returned vector from function in another vector res
vector<int> res= toVector(arr, n);
//using for loop display the vector elements
cout << "The elements of vector are:\n";
for(int i = 0; i< n;i++)
cout << res[i] <<"\n";
return 0;
}
O/P:
The elements of vector are:
10
20
30
40
50
60
70
80
90
100
Code screenshot:
O/P screenshot: