Sign in to follow this  
Endar

Moving a vector element

Recommended Posts

I have a vector of a type that has a few data members of char* which point to strings, the space for which has been allocated on the heap (malloc). I'm wondering what is the best way to move one element to another spot, specifically the front. What is the best way to do this? I just looked at the MSDN page (cd version) and I couldn't see anything obvious. Would I have to do some manual swapping?

Share this post


Link to post
Share on other sites
Assuming you don't need to keep the other objects in the vector in order:
std::swap(myVector[0], myVector[index]);
should do the trick.

Otherwise:
myVector.insert(myVector.begin(), myVector[index]);
myVector.erase(myVector.begin() + index + 1);


If you're doing this often then a list might be a better data structure.

Enigma

Share this post


Link to post
Share on other sites
If you were using a list, you could have used splice.. Are you sure you need a vector? If so, you're stuck with moving it manually - a costly operation if you intend to do it often.

Using a vector, you'll have to get the pointer value, erase it from the container, and re-insert it at the position you want it at.

Edit: beaten ><

Share this post


Link to post
Share on other sites
Quote:
Original post by Enigma
Otherwise:
myVector.insert(myVector.begin(), myVector[index]);
myVector.erase(myVector.begin() + index + 1);



Another option (faster if the item is usually in the first half of the list, slower otherwise) would be to use std::rotate(myVector.begin(), myVector.begin() + index, myVector.begin() + index + 1). I could be off-by-one on that though.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this