There are two different blocks of memory with different size. Is there a way to swap two equal-sized parts in both of them without allocating new memory?
Sure, just use std::swap_ranges
. For example, if you have an std::vector<int> v(100)
and an int array[200];
you could do
std::swap_ranges(std::begin(v), std::end(v), array+50);
To swap the values in the vector with the values in the middle of the array.
To be specific about memory usage: if you have complex iterator or object types, you may need a stack frame for their comparison, dereference, or assignment operators. Whether swap_ranges
requires a stack frame of its own depends on the implementation.
In the example above, I would expect everything to be optimized out to a simple loop. (I tried to profile it, but my simple testcase got optimized out to a series of printf
calls.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With