can i use memshift on vectors the way you do with arrays?

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;
    }
    else if (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;
    }
    else if (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;
	}
}

Last edited on
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) );
why insert/erase? The efficient solution, if I was able to follow your logic correctly, is simply

1
2
3
4
5
6
7
void memswap(int* arr, int src, int dest)
{
    if(src < dest)
        rotate(arr+src, arr+src+1, arr+dest);
    else
        rotate(arr+dest, arr+src, arr+src+1);
}


which you can call with arrays or with vectors (passing &vector[0] as the first argument), or you could make it take iterators:
1
2
3
template<typename RandomAccessIterator>
void memswap(RandomAccessIterator src, RandomAccessIterator dest)
...

Topic archived. No new replies allowed.