I have a long string. In the string, I have two non-overlapping parts. They can have a gap between them. The lengths can be different.
For example a string:
This is a "foo", that is a "bar"
I need to "swap" foo and bar, to get the result:
This is a "bar", that is a "foo"
I know the positions and positions of the ends of the strings to swap.
I was able to figure out this function, by doing three rotates:
void swapInPlace(std::string& data, size_t a, size_t next_a, size_t b, size_t next_b) {
const size_t gap_len = b - next_a;
const size_t b_len = next_b - b;
std::rotate(data.begin()+a, data.begin()+next_a, data.begin()+b);
std::rotate(data.begin()+a+gap_len, data.begin()+b, data.begin()+next_b);
std::rotate(data.begin()+a, data.begin()+a+gap_len, data.begin()+a+gap_len+b_len);
}
This works, and is without an allocation, but is it the best that can be done?
std::swap_rangesand onestd::rotate? Anyway to do any kind of decision some tests (benchmarks) are needed.