KugBuBu
KugBuBu

Reputation: 630

Swap blocks of memory

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?

Upvotes: 5

Views: 4052

Answers (1)

Komi Golov
Komi Golov

Reputation: 3471

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.)

Upvotes: 11

Related Questions