I have this code fragment
int i = 5;
int k = 7;
int * iPtr;
int * jPtr;
int * kPtr;
iPtr = &i;
kPtr = &k;
I am required to swap i and k using the pointers. This is how I’m doing it:
*jPtr = *kPtr ;
*kPtr = *iPtr ;
*iPtr = *jPtr ;
Is this the best way to do it, or is there a better way?
The best way to do that in C++, in my opinion, is with
std::iter_swap():You may think that’s an overkill, but I’d disagree if you include
<algorithm>anyway. Of course, in the case of a homework this answer only holds if the instructor’s intent is to familiarize you with the STL. If the intent is to introduce you to pointers then the best solution is to introduce a temporary variable,j: