Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move list element to the end in STL

Tags:

c++

list

stl

I have already the list pointer of CDrawObject*

std::list<CDrawObject*> elements;

How I can move some element to the end of list. I see STL Algorithms Reference but i don't find this operations. How i can do it?

like image 871
G-71 Avatar asked Feb 06 '11 08:02

G-71


People also ask

How do I find an element in a list STL?

You use std::find from <algorithm> , which works equally well for std::list and std::vector . std::vector does not have its own search/find function. Note that this works for built-in types like int as well as standard library types like std::string by default because they have operator== provided for them.

How do I clear a list in STL?

list::clear() is an inbuilt function in C++ STL which is declared in header file. list::clear(), clears the whole list. In other words the clear() removes all the elements present in the list container and leaves the container with size 0.

What is a list in STL?

Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about a doubly linked list.


2 Answers

Use the list method splice()

void list::splice ( iterator position, list<T,Allocator>& x, iterator i );

Move iterator i from list x into current list at position "position"

Thus to move it to the end put

x.splice( x.end(), x, iter );

(they can both be the same list or different lists as long as the list from which the item is moved has the same type, both T and Allocator)

like image 177
CashCow Avatar answered Oct 24 '22 09:10

CashCow


A std::list is a doubly-linked list, which means you do not have random access to element n. You have to can remove the element, and then use push_back.

like image 26
Itamar Katz Avatar answered Oct 24 '22 09:10

Itamar Katz