I used to use the following function to remove a value from an array and insert it elsewhere:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void memswap(int * arr, int src, int dest) {
// store the element to be moved in a temporary container
int cont = arr[src];
if (src != 0 && src-1 >= dest+1) {
memmove(arr+dest+1,arr+dest, (src - dest)*sizeof(int) );
arr[dest] = cont;
}
elseif (dest != 0 && src+1 <= dest-1) {
memmove(arr+src,arr+src+1, (dest -src - 1)*sizeof(int) );
arr[dest-1] = cont;
}
else {
// source and destination are neighbours and a simple swap will do
arr[src] = arr[dest];
arr[dest] = cont;
}
}
now that I am using vectors I could easily replicate this functionality using insert/erase operators. however, this would create a lot of unnecessary overhead so I was wondering if the above function would still work for a vector, by simply changing the input type:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void memswap(vector<int> & arr, int src, int dest) {
// store the element to be moved in a temporary container
int cont = arr[src];
if (src != 0 && src-1 >= dest+1) {
memmove(arr+dest+1,arr+dest, (src - dest)*sizeof(int) );
arr[dest] = cont;
}
elseif (dest != 0 && src+1 <= dest-1) {
memmove(arr+src,arr+src+1, (dest -src - 1)*sizeof(int) );
arr[dest-1] = cont;
}
else {
// source and destination are neighbours and a simple swap will do
arr[src] = arr[dest];
arr[dest] = cont;
}
}
To get a pointer to the internal buffer of the vector you can use &arr[0] (or arr.data() in C++11). memmove(&arr[0]+dest+1,&arr[0]+dest, (src - dest)*sizeof(int) );