Re: how swap two strings without using 3rd variable? could it be done using construct
If you are dealing with C-style null terminated strings, and have a pointer to the first character of each string, then you could just swap the pointers. If you are dealing with std::string objects, then just use std::swap as the underlying swap is likely to swap pointers rather than perform a full copy with a third string.
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
Re: how swap two strings without using 3rd variable? could it be done using construct
as a general rule... NO.
Swapping in C/C++ always requires a temporary.
std::swap() just works around the issue, it still uses a temporary, you just didn't define it yourself.
You might be able to pull some "weird" binary or mathematical trick to swap SOME types of variables, but chances are this'll be less efficient in the end than using a temporary for the swap.
Re: how swap two strings without using 3rd variable? could it be done using construct
The only situation where it is possible to swap standard null terminated strings without using a 3rd variable is when they are exactly the same size (or the memory allocated for the smaller string is at least that of the larger string). See example below. This also assumes that the max ASCII value of any individual char in the string is 127 otherwise *p1 += *p2 will overflow the bounds of a char.
Re: how swap two strings without using 3rd variable? could it be done using construct
Originally Posted by 2kaud
The only situation where it is possible to swap standard null terminated strings without using a 3rd variable is when they are exactly the same size (or the memory allocated for the smaller string is at least that of the larger string). See example below. This also assumes that the max ASCII value of any individual char in the string is 127 otherwise *p1 += *p2 will overflow the bounds of a char.
Generally we don't post solutions to homework here.
Re: how swap two strings without using 3rd variable? could it be done using construct
Perhaps it doesn't even need to be as nifty as 2kaud's proposal, in case that no temporary string variable (of whatever concrete type) is allowed, while a temporary char variable is...
I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.
This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.
Bookmarks