I have written a program that flips the elements of an array that are next to each other. for example
1, 2, 1, 2
becomes 2, 1, 2, 1
The code I wrote is:
#include <iostream>
template <class T>
void swap(T& a, T& b){
T temp = a;
a = b;
b = temp;
}
template <class T>
void oReverse(T* p, int size){
for(T* e = p + size; p < e; p+=1){
swap(*p, *p++);
}
}
int main(){
int arr[] = {1,2,1,2,1,2};
oReverse(arr, 6);
for(int i = 0; i < 6; i++){
std::cout << arr[i] << " ";
}
return 0;
}
The oReverse()
function takes care of the pointer magic.
The thing i couldn't understand is: Why does swap(*p, *p++)
increment p by one.
At first I wrote p+=2 in the for loop, but it didn't work well, but it does with p++.
I thought the program would swap p and p++ then increment p by 2 then swap p and p++ again and again.
I hope i explained the problem clearly enough.