The list in the C + + Standard Template Library is a non-intrusive linked list, and when we delete objects in the container through objects, we need to find the iterator from beginning to end, and finally delete the object by iterator. This makes it a bit slower to delete objects in the container, so it implements an intrusive list.
Intrusive_list.h
#ifndef _intrusive_list_h_#define_intrusive_list_h_//Intrusive linked listtemplate<classT>classIntrusive_list { Public: structNode; //iterators classIterator { Public: iterator (Node*node): M_node (node) {} iterator&operator++() { if(m_node) M_node= m_node->M_next; return* This; } iterator&operator--() { if(m_node) M_node= m_node->M_prev; return* This; } BOOL operator== (Constiterator& iter) {returnM_node = =Iter.m_node;} BOOL operator!= (Constiterator& iter) {return!operator==(ITER);} T&operator*() {return*M_node;} T*operator() {returnM_node;} Private: Node*M_node; }; Intrusive_list (): M_head (nullptr), M_tail (nullptr) {}~intrusive_list () {Node* node =M_head; while(node) {node* Next = node->M_next; Deletenode; Node=Next; } } //adding Objectstemplate<class... Args>T*Add (args ... args) {Node* node =NewNode (args ...); if(M_head &&m_tail) {Node->m_prev =M_tail; M_tail->m_next =node; M_tail=node; } Else{M_head=node; M_tail=node; } returnnode; } //removing Objects voidRemove (t*ptr) {Node* node = (node*) ptr; ASSERT (Node-m_valid); if(M_head = =node) {M_head= m_head->M_next; } if(M_tail = =node) {M_tail= m_tail->M_prev; } if(node->m_prev) Node->m_prev->m_next = node->M_next; if(node->m_next) Node->m_next->m_prev = node->M_prev; Deletenode; } iterator Begin () {returniterator (m_head);} Iterator End () {returniterator (nullptr);}Private: structNode: PublicT {Template<class... Args>Node (args ... args): T (args ...), M_valid (true), M_prev (nullptr), M_next (nullptr) {}BOOLM_valid; Node*M_prev; Node*M_next; }; Node*M_head; Node*M_tail;};#endif
Test.cpp
int_tmain (intARGC, _tchar*argv[]) { structPerson {person (Const Char*name): M_name (name) {} std::stringM_name; intM_age; }; Intrusive_list<Person>lst; person* P0 = Lst.add (" One"); Lst.add ("2"); Lst.add ("3"); Lst.add ("4"); Lst.add ("5"); person* P1 = Lst.add ("6"); Lst.remove (P0); Lst.remove (p1); for(Auto iter = Lst.begin (); ITER! = Lst.end (); + +ITER) {Std::cout<< Iter->m_name <<Std::endl; } return 0;}
C + + intrusive linked list