I am trying to learn patterns in C ++, and one of the things I tried was to encode a map function, such as the ones you usually find in functional languages. The idea was something like this:
template <class X> X * myMap(X * func(X), X * array, int size)
{
X * temp;
for(int i = 0, i < size, i++) {temp[i] = (*func)(array[i]);}
return temp;
}
But when I try to use this in:
int test(int k) { return 2 * k;}
int main(void)
{
int k[5] = {1,2,3,4,5};
int *q = new int[5];
q = myMap(&test, k, 5);
for(int i=0; i<5; i++) {cout << q[i];}
delete [] q;
return 0;
}
When compiling, I got a type mismatch error:
main.cpp:25: error: no matching function for call to ‘myMap(int (*)(int), int [5], int)’
I tried changing it to:
int main(void)
{
int *k = new int[5];
int *q = new int[5];
for(int i=0; i<5;i++) {k[i] = i;}
q = myMap(&test, k, 5);
for(int i=0; i<5; i++) {cout << q[i];}
delete [] q;
return 0;
}
The error message changes to:
main.cpp:26: error: no matching function for call to ‘myMap(int (*)(int), int*&, int)’
This is probably something very wrong, but I can not find where.
EDIT: errors in which: 1) I was silent about the function pointer. This is X (* func) (X) instead of X * func (X). 2) forgot to highlight temp. Need to do X * temp = new X[size]. 3) are there more errors?