How do I turn the fucntion sumVec into a template function [closed]
Clash Royale CLAN TAG#URR8PPP
How do I turn the fucntion sumVec into a template function [closed]
I got this code (I know it's in Spanish I can translate if needed) where they give me the function SumVec. What the function does is it receives as parameters two arrays (integer pointers) and an integer (size) and returns a pointer to the sum of the two vectors or arrays. I have to convert it so it can receive any type, not just integer. I know that you do that with a template by using "template " but I've only done simple classes I don't know how to do it with pointers. Any help?
The code
#include <iostream>
#include <cstdlib>
using namespace std;
int * sumVec(int*, int*, int);
int main()
int n, nCol, nFil = 0;
//Arreglo unidimensional din�mico
int *ptr, *suma, size;
cout << "Cuantos Items va a procesar:";
cin >> size;
ptr = new int[size];//Asignando memoria al arreglo
//input
for (int i = 0;i<size;i++)
cout << "Ingrese el numero de Items NO." << i + 1 << " :";
cin >> ptr[i];
//Mostrando el contenido del archivo
for (int i = 0;i<size;i++) cout << "nItem. NO." << i + 1 << " :" << ptr[i];
cout << endl;
suma = sumVec(ptr, ptr, size);
//Mostrando el contenido de la suma
for (int i = 0;i<size;i++) cout << "nSuma Item. NO." << i + 1 << " :" << suma[i];
cout << endl;
deleteptr;//Liberando la memoria asignada al arreglo unidimensional.
return 0;
int * sumVec(int* Array1, int* Array2, int Size)
int *ptr = new int[Size];
for(int i=0; i<Size; i++)
ptr[i]= Array1[i] + Array2[i];
return ptr;
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.
std::vector
std::transform
Because they want me to do it that way
– Miguel Santiago
Aug 10 at 15:10
who is "they" ?
– user463035818
Aug 10 at 15:10
the people that are "teaching" me
– Miguel Santiago
Aug 11 at 16:12
1 Answer
1
Granted your goal is to rewrite the sumVec
function, you simply need to prefix your function with template<typename T>
and replace every int
by T
in your function. But I would recommend keeping int
for the index type.
sumVec
template<typename T>
int
T
int
template<typename T>
T * sumVec(T* Array1, T* Array2, int Size)
T *ptr = new T[Size];
for(int i=0; i<Size; i++)
ptr[i]= Array1[i] + Array2[i];
return ptr;
Please note you must define your function before calling it, e.g. https://ideone.com/ZAyCLs
why do you need to reinvent the wheel? Simply use
std::vector
andstd::transform
– user463035818
Aug 10 at 15:04