Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

std::rotate substitute

36 views
Skip to first unread message

bitrex

unread,
Oct 18, 2018, 7:23:57 PM10/18/18
to
I need an implementation of rotate for a microprocessor platform where I
have C++11 compiler but really nothing else available to work with. I'd
like to be able to rotate the elements of a short array of characters of
arbitrary length e.g. ABCD -> BCDA -> CDAB etc.

Something like the following should be good enough, but what's good to
use for "swap"? "algorithm" is a non-starter here, too.

#include <algorithm>

string rotate(string s) {
for (int i = 1; i < s.size(); i++)
swap(s[i-1], s[i]);
return s;
}

bitrex

unread,
Oct 18, 2018, 7:27:08 PM10/18/18
to
Perhaps the old "hack":

#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))

?

Alf P. Steinbach

unread,
Oct 18, 2018, 9:16:06 PM10/18/18
to
On 19.10.2018 01:23, bitrex wrote:
> I need an implementation of rotate for a microprocessor platform where I
> have C++11 compiler but really nothing else available to work with. I'd
> like to be able to rotate the elements of a short array of characters of
> arbitrary length e.g. ABCD -> BCDA -> CDAB etc.

If the microprocessor is 32-bit or better, just use its rotate instruction.


> Something like the following should be good enough, but what's good to
> use for "swap"? "algorithm" is a non-starter here, too.

Don't move data by repeated swapping. For moving, move.


> #include <algorithm>
>
> string rotate(string s) {
>   for (int i = 1; i < s.size(); i++)
>     swap(s[i-1], s[i]);
>   return s;
> }

You want a mutating routine for efficiency, not a function.

Like,

void rotate_buffer( char* buf, int size )
{
// Use memmov for the moving.
}

void rotate( string& s )
{
rotate_buffer( s.data(), s.size() );
}

Cheers & hth.,

- Alf

David Brown

unread,
Oct 19, 2018, 2:43:06 AM10/19/18
to
No. Just.. no.


(Alf has already posted the ideas I had.)

Juha Nieminen

unread,
Oct 19, 2018, 10:27:30 AM10/19/18
to
bitrex <us...@example.net> wrote:
> Perhaps the old "hack":
>
> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))

Which at least in modern architectures is slower than the "naive"
swap.

Juha Nieminen

unread,
Oct 19, 2018, 10:30:16 AM10/19/18
to
bitrex <us...@example.net> wrote:
> string rotate(string s) {
> for (int i = 1; i < s.size(); i++)
> swap(s[i-1], s[i]);
> return s;
> }

Why swapping? You are performing tons of unnecessary assignments.
In fact, you are performing twice as many as would be needed.
(For a string of length n, you only need n+1 assignments,
not (n-1)*3 assignments as you are doing there.)

bitrex

unread,
Oct 20, 2018, 1:24:59 AM10/20/18
to
Ah, right, memmove! I've definitely got string.h, it's been a long time
since I've had to resort to dusty ol' C...
0 new messages