what is the easiest way to shift array "abcdefg" to "defgabc"?
Printable View
what is the easiest way to shift array "abcdefg" to "defgabc"?
You could use std::rotate from <algorithm>.
is there something else than that? like directly shifting letters from one end to the other?
Sure, if you want you can implement the rotation manually.Quote:
Originally Posted by gamers18
Yes you can do a shift on the elements with your own function.
In general you have to have an array big enough to handle the shifting. In the example we want to end up with something like:
abcdefg
bcdefga
cdefgab
defgabc
The easiest way to do that is to have space in reserve at the end of the array... this will help you when you actually copy the characters in the front of the pivot ('d') to make space for the characters behind the pivot ('d') and place them in their new positions at the end of the array. The shifting part comes in when you have to scoot the pivot character and all the characters behind it into their new places.
You don't have to move one character at a time either. Using a group of three might be easier to program, but using one character at a time was easiest for me to explain what you need to do. That should give you plenty to think about. HTH.
Or there's another easy way, with no extra space required:
Reverse each "half" of the string, where by half, I mean split at the point of rotation.
Reverse the whole thing.
I.e
abcdefg -> cbagfed -> defgabc