Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap blocks of memory

Tags:

c++

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?

like image 803
KugBuBu Avatar asked Jan 05 '14 14:01

KugBuBu


1 Answers

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

like image 81
Anton Golov Avatar answered Oct 14 '22 06:10

Anton Golov