Jump to content
  • Advertisement
Sign in to follow this  
Endar

Moving a vector element

This topic is 4866 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Zahlman - hmmm, very clever. I had never thought of using rotate that way.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!