Would it be ok to write something like the code below?
template<class Temp, class Temp2>
void swaps_arr(Temp* arr, Temp2* arr2, int N){
for (int i = 0; i < N; i )
{
Temp currentArrItem = arr[i];
arr[i] = (Temp)arr2[i];
arr2[i] = (Temp2)currentArrItem;
}
}
I wrote a show method.
template<class Temp, class Temp2>
void show(Temp* arr, Temp2* arr2, int N){
for (int i = 0; i < N; i ) cout << arr[i] << " "; cout << endl;
for (int i = 0; i < N; i ) cout << arr2[i] << " "; cout << endl;
}
Then I called these function as below;
int main(int argc, char const *argv[])
{
int N = 8;
int* arr = new int[N];
char * arr2 = new char[N];
for (int i = 0; i < N; i ) arr[i] = i 1;
for (int i = 0; i < N; i ) arr2[i] = 'A';
show(arr, arr2, N);
swaps_arr(arr, arr2, N);
cout << "After swapping" << endl;
show(arr, arr2, N);
}
It works for double and int. But for char it doesn't.
CodePudding user response:
It works for double and int. But for char it doesn't.
It works, but you may not be getting the output you expect.
First, you are filling your array of ints with the numbers 1 to 8:
for (int i = 0; i < N; i ) arr[i] = i 1;
Then you are swapping both arrays, so now you have an array of chars with the values 1 to 8.
Finally, you print that array:
for (int i = 0; i < N; i ) cout << arr2[i] << " "; cout << endl;
Every arr2[i]
is printed as a char of value 1 to 8. Those are "control characters" (delete, escape, end of line...). You would see "printable characters" if the values of those characters were between 32 and 126.
Just change your example filling the array of ints with values that correspond to "printable characters":
for (int i = 0; i < N; i ) arr[i] = i 'A';
And you will get this output:
65 66 67 68 69 70 71 72
A A A A A A A A
After swapping
65 65 65 65 65 65 65 65
A B C D E F G H
Another way of implementing the swapping function would be:
- Using the
transform
algorithm to loop througharr
andarr2
. - Using
exchange
to copy the contents of each elementx
inarr
to anx2
inarr2
, and return the old value ofx2
. - Assigning that old value of
x2
tox
. This is done bytransform
getting the lambda's return value and writing it toarr
(4th argument).
template<class Temp, class Temp2>
void swaps_arr(Temp* arr, Temp2* arr2, int N)
{
std::transform(arr, arr N, arr2, arr,
[](Temp& x, Temp2& x2){ return std::exchange(x2, x); });
}
CodePudding user response:
It will only work, if Temp and Temp2 are from the same class. If not, there will be some behaviour I imagine you do not want, like implicit casting.
template<class Temp>
void swaps_arr(Temp* arr, Temp* arr2, int N){
for (int i = 0; i < N; i )
{
Temp currentArrItem = arr[i];
arr[i] = (Temp)arr2[i];
arr2[i] = (Temp2)currentArrItem;
}
}