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

Started by
1 comment, last by Antheus 16 years, 8 months ago
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?
Advertisement
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.
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.

This topic is closed to new replies.

Advertisement