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 using a template. You may assume that the array elements have a valid copy constructor. Please explain every line of code to me
Here is the code:
# include <iostream>
# include <vector>
using namespace std;
//define a template function which takes any type T
template <typename T>
//the return value is a vector containing elements of type T
//the argument is a pointer to elements of type T, and n
vector<T> toVector(T* a, int n) {
//define a vector
vector<T> v;
//iterate over the array in the pointer
for (int i=0; i<n; i++) {
//add i to get the pointer to ith element
//then dereference to get the value
v.push_back(*(a+i));
}
//return the vector
return v;
}
int main() {
//this is for testing
//define an int array and char array
int* intArray = new int[3];
//initialize some values
*intArray = 4;
*(intArray+1) = 2;
*(intArray+2) = 0;
char* charArray = new char[3];
*charArray = 'c';
*(charArray+1) = 'a';
*(charArray+2) = 't';
//use the toVector function for both arrays
vector<int> v1 = toVector(intArray, 3);
vector<char> v2 = toVector(charArray, 3);
//now print the two vectors
for (int i=0; i<3; i++) {
cout << v1[i] << " ";
}
cout << endl;
for (int i=0; i<3; i++) {
cout << v2[i] << " ";
}
cout << endl;
return 0;
}
Here is a screenshot of the code:
Here is the output of the code:
Comment in case of any doubts.