This question is similar to the one posed here however, this answer does not work for my question and it is slightly different.
What I am trying to do would best be shown in code:
//this would be a copy version:
int main(){
std::vector<uint32_t> order = {0,2,5,6,9,10,1,3,4,7,8,11};
std::vector<uint32_t> example = {0,1,2,3,4,5,6,7,8,9,10,11};
std::vector<uint32_t> output(order.size());
for(uint32_t i = 0; i < order.size(); ++i){
output[i] = example[order[i]];
}
}
//output comes out to {0,2,5,6,9,10,1,3,4,7,8,11}
However, when I try to implement an in-place version using the reorder code from the link above as such:
void reorder(std::vector<uint32_t> &v, std::vector<uint32_t> const &order ) {
for ( int s = 1, d; s < order.size(); ++ s ) {
for ( d = order[s]; d < s; d = order[d] ) ;
if ( d == s ) while ( d = order[d], d != s ) std::swap( v[s], v[d] );
}
}
int main(){
std::vector<uint32_t> order = {0,2,5,6,9,10,1,3,4,7,8,11};
std::vector<uint32_t> example = {0,1,2,3,4,5,6,7,8,9,10,11};
reorder(example, order);
}
//example = {0,6,1,7,8,2,3,9,10,4,5,11,}
How could I implement an in-place version of what I am trying to accomplish without copying memory?
Edit
I wanted to make something more clear, the vector example
from the code can be arbitrary elements, I just happened to make them initialized the way I did for the ease of checking them. This would be entirely valid:
std::vector<uint32_t> example = {300,12,21,34,47,15,61,57,82,94,1,2};
order
andexample
will always contain the same number of elements- It is not guaranteed that
order
andexample
store the same datatype - It is also guaranteed that
order
stores unique values - It is also guaranteed that
order
will always be the datatypeuint32_t
order
is always going to be in a range from 0 ton-1
wheren
is the size ofexample
, Each of those numbers, exactly once, and nothing outside of that range. (like it does in the example code)- The actual order of that range is entirely random, has nothing to do with even or odd indices coming in any order.