Saturday, June 6, 2026

Understanding std::rotate

While working on the future version of my C++20 WinDlg library, I stumbled upon the need to shift characters within a string. My first impulse was to use memmove, but hey, there should be a C++ way to do this.

In fact, std::rotate seemed to be the appropriate fit – safe and sound –, but turns out I had a different idea on how it would work, and it took me a while to properly understand it. The central idea is: you take the interval [it1 it2) and move it right, so it will end at it3). Everything beyond it3 will be placed at the beginning. Thus it actually “rotates” to the left.

Examples:

std::wstring s = L"01234";

std::rotate(s.begin(), s.begin() + 1, s.end()); // 12340
std::rotate(s.begin(), s.begin() + 2, s.end()); // 23401
std::rotate(s.begin(), s.begin() + 4, s.end()); // 40123

std::rotate(s.begin() + 1, s.begin() + 2, s.end()); // 02341
std::rotate(s.begin() + 3, s.begin() + 4, s.end()); // 01243

No comments:

Post a Comment