Sign in to follow this  
fpsgamer

C++, std::list and std::swap

Recommended Posts

fpsgamer    856
If you have a linked list, you can quickly swap elements by switching around the appropriate pointers. But if you have an std::list and apply std::swap, (which happens to be the only way I know how to swap elements in a container), it will swap elements by performing a few copy operations. Is there a way I can get an std::list to perform a swap using pointers instead?

Share this post


Link to post
Share on other sites
SiCrane    11839
You could probably do it with list::splice(). However, if the performance of the swap behavior bothers you, you may want to consider using a list of (smart) pointers instead of storing the elements by value.

Share this post


Link to post
Share on other sites
Antheus    2409
Quote:
Original post by fpsgamer
If you have a linked list, you can quickly swap elements by switching around the appropriate pointers.

But if you have an std::list and apply std::swap, (which happens to be the only way I know how to swap elements in a container), it will swap elements by performing a few copy operations.

Is there a way I can get an std::list to perform a swap using pointers instead?


By putting pointers inside the container in the first place. (std::list< X* >)

Swap is swap - there's nothing you can do about it, you have no control over how things are stored internally, or whether you may just swap pointers.

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