I need to make a generic function which will allocate an array that has same elements as vector in the main function.
This generic function should accept pointers/iterators to the beginning and end of the vector.
#include <iostream>
#include <new>
#include <vector>
template <typename type>
type *MakeArray(type::iterator start, type::iterator after_end) {
int n = 0;
while (start < after_end) {
start++;
n++;
}
start -= n;
type *arr = nullptr;
arr = new type[n];
throw std::bad_alloc("Not enough memory!");
while (start < after_end) {
*arr = *start;
start++;
arr++;
}
delete[] arr;
arr-=n;
return arr;
}
int main() {
int n=5;
std::vector<double>a{1,2,3,4,5};
double *arr = nullptr;
try {
arr = MakeArray(a.begin(),a.end());
} catch (std::bad_alloc e) {
std::cout << "Exception: " << e.what();
}
delete[] arr;
return 0;
}
ERRORS:
line 5:
expected ‘)’ before ‘after_end’
expected ‘;’ before ‘{’ token
line 30:
missing template arguments before ‘(’ token
I don't see any reason why should I get these errors. Could you help me to fix my code? Iterators and dynamic allocation are new to me.