|  | 
|  |  |  |  
| Category: containers |  | Component type: type |  
DescriptionAn slistis a singly linked list: a list where each element is linked to the next element, but not to the previous element. [1] That is, it is a Sequence that supports forward but not backward traversal, and (amortized) constant time insertion and removal of elements.Slists, likeLists, have the important property that insertion and splicing do not invalidate iterators to list elements, and that even removal invalidates only the iterators that point to the elements that are removed. The ordering of iterators may be changed (that is,slist<T>iteratormight have a different predecessor or successor after a list operation than it did before), but the iterators themselves will not be invalidated or made to point to different elements unless that invalidation or mutation is explicit. [2] The main difference between slistandListis thatList's iterators are BidirectionalIterator, whileslist's iterators are ForwardIterator. This means thatslistis less versatile thanList; frequently, however, BidirectionalIterator are unnecessary. You should usually useslistunless you actually need the extra functionality ofList, because singly linked lists are smaller and faster than double linked lists. Important performance note: like every other Sequence, slistdefines the member functionsinsertanderase. Using these member functions carelessly, however, can result in disastrously slow programs. The problem is thatinsert's first argument is an iteratorpos, and that it inserts the new element(s) beforepos. This means thatinsertmust find the iterator just beforepos; this is a constant-time operation forList, sinceListhas bidirectional iterators, but forslistit must find that iterator by traversing the list from the beginning up topos. In other words:insertanderaseare slow operations anywhere but near the beginning of theslist. Slistprovides the member functionsinsert_afteranderase_after, which are constant time operations: you should always useinsert_afteranderase_afterwhenever possible. If you find thatinsert_afteranderase_afteraren't adequate for your needs, and that you often need to useinsertanderasein the middle of the list, then you should probably useListinstead ofslist.
 
DefinitionDefined in the header slist, and in the backward-compatibility header slist.h. The slistclass, and the slist header, are an SGI extension; they are not part of the C++ standard. 
Exampleint main() {
  slist<int> L;
  L.push_front(0);
  L.push_front(1);
  L.insert_after(L.begin(), 2);
  copy(L.begin(), L.end(),        
       ostream_iterator<int>(cout, " "));
  cout << endl;
  slist<int>::iterator back = L.previous(L.end());
  back = L.insert_after(back, 3); 
  back = L.insert_after(back, 4);
  back = L.insert_after(back, 5);
  copy(L.begin(), L.end(),        
       ostream_iterator<int>(cout, " "));
  cout << endl;
}
Template parameters
| Parameter | Description | Default |  
| T | The slist's value type: the type of object that is stored in the list. |  |  
| Alloc | The slist's allocator, used for all internal memory management. | Allocators |  
Model ofFrontInsertionSequence  
Type requirementsNone, except for those imposed by the requirements of FrontInsertionSequence.  
Public base classesNone.  
Members
| Member | Where defined | Description |  
| value_type | Container | The type of object, T, stored in theslist. |  
| pointer | Container | Pointer to T. |  
| reference | Container | Reference to T |  
| const_reference | Container | Const reference to T |  
| size_type | Container | An unsigned integral type. |  
| difference_type | Container | A signed integral type. |  
| iterator | Container | Iterator used to iterate through an slist. |  
| const_iterator | Container | Const iterator used to iterate through an slist. |  
| iterator begin() | Container | Returns an iteratorpointing to the beginning of theslist. |  
| iterator end() | Container | Returns an iteratorpointing to the end of theslist. |  
| const_iterator begin() const | Container | Returns a const_iteratorpointing to the beginning of theslist. |  
| const_iterator end() const | Container | Returns a const_iteratorpointing to the end of theslist. |  
| size_type size() const | Container | Returns the size of the slist. Note: you should not assume that this function is constant time. It is permitted to be O(N), where N is the number of elements in theslist. If you wish to test whether anslistis empty, you should writeL.empty()rather thanL.size() == 0. |  
| size_type max_size() const | Container | Returns the largest possible size of the slist. |  
| bool empty() const | Container | trueif theslist's size is0. |  
| slist() | Container | Creates an empty slist. |  
| slist(size_type n) | Sequence | Creates an slistwithnelements, each of which is a copy ofT(). |  
| slist(size_type n, const T& t) | Sequence | Creates an slist with ncopies oft. |  
| slist(const slist&) | Container | The copy constructor. |  
| [3]template <class InputIterator>
slist(InputIterator f, InputIterator l) 
 | Sequence | Creates an slistwith a copy of a range. |  
| ~slist() | Container | The destructor. |  
| slist& operator=(const slist&) | Container | The assignment operator |  
| void swap(slist&) | Container | Swaps the contents of two slists. |  
| reference front() | FrontInsertionSequence | Returns the first element. |  
| const_reference front() const | FrontInsertionSequence | Returns the first element. |  
| void push_front(const T&) | FrontInsertionSequence | Inserts a new element at the beginning. |  
| void pop_front() | FrontInsertionSequence | Removes the first element. |  
| iterator previous(iterator pos) | slist | See below |  
| const_iterator previous(const_iterator pos) | slist | See below |  
| iterator insert(iterator pos, const T& x) | Sequence | Inserts xbeforepos. |  
| [3]template<class InputIterator>
void insert(iterator pos, InputIterator f, InputIterator l)
 | Sequence | Inserts the range [first, last)beforepos. |  
| void insert(iterator pos,
            size_type n, const value_type& x)
 | Sequence | Inserts ncopies ofxbeforepos. |  
| iterator erase(iterator pos) | Sequence | Erases the element at position pos. |  
| iterator erase(iterator first, iterator last) | Sequence | Erases the range [first, last) |  
| void clear() | Sequence | Erases all of the elements. |  
| void resize(n, t = T()) | Sequence | Inserts or erases elements at the end such that the size becomes n. |  
| iterator insert_after(iterator pos) | slist | See below. |  
| iterator insert_after(iterator pos, const value_type& x) | slist | See below. |  
| template<class InputIterator>
void insert_after(iterator pos,
                  InputIterator f, InputIterator l)
 | slist | See below. |  
| void insert_after(iterator pos, 
                  size_type n, const value_type& x)
 | slist | See below. |  
| iterator erase_after(iterator pos) | slist | See below. |  
| iterator erase_after(iterator before_first, iterator last) | slist | See below. |  
| void splice(iterator position, slist& L) | slist | See below. |  
| void splice(iterator position, slist& L, iterator i) | slist | See below. |  
| void splice(iterator position, slist& L, iterator f, iterator l) | slist | See below. |  
| void splice_after(iterator pos, iterator prev) | slist | See below. |  
| void splice_after(iterator pos, 
                  iterator before_first, 
                  iterator before_last)
 | slist | See below. |  
| void remove(const T& value) | slist | See below. |  
| void unique() | slist | See below. |  
| void merge(slist& L) | slist | See below. |  
| void sort() | slist | See below. |  
|  | ForwardContainer | Tests two slists for equality. This is a global function, not a member function. |  
|  | ForwardContainer | Lexicographical comparison. This is a global function, not a member function. |  
New membersThese members are not defined in the FrontInsertionSequence requirements, but are specific to slist: 
| Function | Description |  
| iterator previous(iterator pos) | posmust be a valid iterator in*this. The return value is an iteratorprevsuch that++prev == pos. Complexity: linear in the number of iterators in the range[begin(), pos). |  
| const_iterator previous(const_iterator pos) | posmust be a valid iterator in*this. The return value is an iteratorprevsuch that++prev == pos. Complexity: linear in the number of iterators in the range[begin(), pos). |  
| iterator insert_after(iterator pos) | posmust be a dereferenceable iterator in*this. (That is,posmay not beend().) Inserts a copy ofT()immediately followingpos. The return value is an iterator that points to the new element. Complexity: constant time. |  
| iterator insert_after(iterator pos,
                      const value_type& x)
 | posmust be a dereferenceable iterator in*this. (That is,posmay not beend().) Inserts a copy ofximmediately followingpos. The return value is an iterator that points to the new element. Complexity: constant time. |  
| template<class InputIterator>
void insert_after(iterator pos,
                  InputIterator f, InputIterator l)
 | Inserts elements from the range [f, l)immediately followingpos. Complexity: linear inlast - first. |  
| void insert_after(iterator pos, 
                  size_type n, const value_type& x)
 | Inserts ncopies ofximmediately followingpos. Complexity: linear inn. |  
| iterator erase_after(iterator pos) | Erases the element pointed to by the iterator following pos. Complexity: constant time. |  
| iterator erase_after(iterator before_first, iterator last) | Erases all elements in the range [before_first + 1, last). Complexity: linear inlast - (before_first + 1). |  
| void splice(iterator position, 
            slist<T, Alloc>& x);
 | positionmust be a valid iterator in*this, andxmust be an slist that is distinct from*this. (That is, it is required that&x != this.) All of the elements ofxare inserted beforepositionand removed fromx. All iterators remain valid, including iterators that point to elements ofx. [4] Complexity: proportional toc1 (position - begin()) + c2(x.size()), wherec1andc2are unknown constants. |  
| void splice(iterator position, 
            slist<T, Alloc>& x,
            iterator i);
 | positionmust be a valid iterator in*this, andimust be a dereferenceable iterator inx.Splicemoves the element pointed to byifromxto*this, inserting it beforeposition. All iterators remain valid, including iterators that point to elements ofx. [4] Ifposition == iorposition == ++i, this function is a null operation. Complexity: proportional toc1 (position - begin()) + c2 (i - x.begin()), wherec1andc2are unknown constants. |  
| void splice(iterator position, 
            slist<T, Alloc>& x,
            iterator f, iterator l);
 | positionmust be a valid iterator in*this, and[first, last)must be a valid range inx.positionmay not be an iterator in the range[first, last).Splicemoves the elements in[first, last)fromxto*this, inserting them beforeposition. All iterators remain valid, including iterators that point to elements ofx. [4] Complexity: proportional toc1 (position - begin()) + c2 (f - x.begin()) + c3 (l - f), wherec1,c2, andc3are unknown constants. |  
| void remove(const T& val); | Removes all elements that compare equal to val. The relative order of elements that are not removed is unchanged, and iterators to elements that are not removed remain valid. This function is linear time: it performs exactlysize()comparisons for equality. |  
| void splice_after(iterator pos, iterator prev) | posmust be a dereferenceable iterator in*this, andprevmust be a dereferenceable iterator either in*thisor in some otherslist. (Note: "dereferenceable iterator" implies that neitherposnorprevmay be an off-the-end iterator.) Moves the element followingprevto*this, inserting it immediately afterpos. Complexity: constant time. |  
| void splice_after(iterator pos, 
                  iterator before_first, 
                  iterator before_last)
 | posmust be a dereferenceable iterator in*this, andbefore_firstandbefore_lastmust be dereferenceable iterators either in*thisor in some otherslist. (Note: "dereferenceable iterator" implies that none of these iterators may be off-the-end iterators.) Moves the elements in the range[before_first + 1, before_last + 1)to*this, inserting them immediately afterpos. Complexity: constant time. |  
| [5]template<class Predicate> 
void remove_if(Predicate p); 
 | Removes all elements *isuch thatp(*i)is true. The relative order of elements that are not removed is unchanged, and iterators to elements that are not removed remain valid. This function is linear time: it performs exactlysize()applications ofp. |  
| void unique(); | Removes all but the first element in every consecutive group of equal elements. The relative order of elements that are not removed is unchanged, and iterators to elements that are not removed remain valid. This function is linear time: it performs exactly size() - 1comparisons for equality. |  
| [5]template<class BinaryPredicate>
void unique(BinaryPredicate p); 
 | Removes all but the first element in every consecutive group of equivalent elements, where two elements *iand*jare considered equivalent ifp(*i, *j)is true. The relative order of elements that are not removed is unchanged, and iterators to elements that are not removed remain valid. This function is linear time: it performs exactlysize() - 1comparisons for equality. |  
| void merge(slist<T, Alloc>& x); | Both *thisandxmust be sorted according tooperator<, and they must be distinct. (That is, it is required that&x != this.) This function removes all ofx's elements and inserts them in order into*this. The merge is stable; that is, if an element from*thisis equivalent to one fromx, then the element from*thiswill precede the one fromx. All iterators to elements in*thisandxremain valid. This function is linear time: it performs at mostsize() + x.size() - 1comparisons. |  
| [5]template<class BinaryPredicate>
void merge(slist<T, Alloc>& x, 
           BinaryPredicate Comp); 
 | Compmust be a comparison function that induces a strict weak ordering (as defined in the LessThanComparable requirements) on objects of typeT, and both*thisandxmust be sorted according to that ordering. The slistsxand*thismust be distinct. (That is, it is required that&x != this.) This function removes all ofx's elements and inserts them in order into*this. The merge is stable; that is, if an element from*thisis equivalent to one fromx, then the element from*thiswill precede the one fromx. All iterators to elements in*thisandxremain valid. This function is linear time: it performs at mostsize() + x.size() - 1applications ofComp. |  
| void reverse(); | Reverses the order of elements in the slist. All iterators remain valid and continue to point to the same elements. [6] This function is linear time. |  
| void sort(); | Sorts *thisaccording tooperator<. The sort is stable, that is, the relative order of equivalent elements is preserved. All iterators remain valid and continue to point to the same elements. [7] The number of comparisons is approximatelyN log N, whereNis theslist's size. |  
| [5]template<class BinaryPredicate>
void sort(BinaryPredicate comp); 
 | Compmust be a comparison function that induces a strict weak ordering (as defined in the LessThanComparable requirements) on objects of typeT. This function sorts the slist*thisaccording toComp. The sort is stable, that is, the relative order of equivalent elements is preserved. All iterators remain valid and continue to point to the same elements. [7] The number of comparisons is approximatelyN log N, whereNis theslist's size. |  
Notes[1] The lists in such languages as Common Lisp, Scheme, and ML are singly linked lists. In some programming languages, almost all data structures are represented as singly linked lists.  [2] A comparison with Vectoris instructive. Suppose thatiis a validVector<T>iterator. If an element is inserted or removed in a position that precedesi, then this operation will either result inipointing to a different element than it did before, or else it will invalidateientirely. (AVector<T>iteratorwill be invalidated, for example, if an insertion requires a reallocation.) However, suppose thatiandjare both iterators into a Vector, and there exists some integernsuch thati == j + n. In that case, even if elements are inserted into the vector andiandjpoint to different elements, the relation between the two iterators will still hold. Anslistis exactly the opposite: iterators will not be invalidated, and will not be made to point to different elements, but, forslistiterators, the predecessor/successor relationship is not invariant. [3] This member function relies on member template functions, which at present (early 1998) are not supported by all compilers. If your compiler supports member templates, you can call this function with any type of InputIterator. If your compiler does not yet support member templates, though, then the arguments must either be of type const value_type*or of typeslist::const_iterator. [4] A similar property holds for all versions of insert()anderase().Slist<T, Alloc>insert()never invalidates any iterators, andslist<T, Alloc>erase()only invalidates iterators pointing to the elements that are actually being erased. [5] This member function relies on member template functions, which at present (early 1998) are not supported by all compilers. You can only use this member function if your compiler supports member templates.  [6] The reversealgorithm works only for BidirectionalIterator. Even ifreversewere extended to work with ForwardIterator, however, it would still be useful to have thereversemember function: it has different iterator invalidation semantics. That is, thereversemember function preserves the value that each iterator points to. Note also that the algorithmreverse(L.begin(), L.end())usesT's assignment operator, but the member functionL.reverse()does not. [7] The sortalgorithm works only for RandomAccessIterator. In principle, however, it would be possible to write a sort algorithm that also accepted ForwardIterator. Even if there were such a version ofsort, it would still be useful forslistto have asortmember function. That is,sortis provided as a member function not only for the sake of efficiency, but also because of the property that it preserves the values that list iterators point to. 
See alsoBidirectionalIterator, ReversibleContainer, Sequence, List,Vector |