What are Lists?
- List class supports a bidirectional linear list. Unlike a vector, which supports random access, a list can be accessed sequentially only. Since lists are bidrectional, they may be accessed front to back or back to front.
- The template specification of list is :
template < class T, class Allocator = allocator<T>> class list
- Here, T is the type of data stored in the list.
- It has the following constructors :
explicit list (const Allocator &a = Allocator());
// Constructs empty list.
explicit list (size_type num, const T &val=T(), const Allocator &a = Allocator());
// constructs list that has num elements with the value val.
list (const list <T, Allocator> &ob);
// constructs a list that has same elements as ob
template <class InIter> list(InIter start, InIter end, const Allocator &a = Allocator());
// constructs a list that contains the elements in the range specified by the iterators start and end.
Examples :list <int> iv; //create zero length int list.
list <char> cv(5); //create 5 element char list.
list <char> cv(5, ‘x’); //initializes a 5-element char list.
list <int> iv; //create a vector from an int list.
- Some of the commonly used list functions are :
push_back() : To put elements to the list.
push_front() : To put elements to the front of the list.
insert() : To put elements in the middle of the list.
splice() : Two lists can be joined using splice().
merge() : One list can be merged into another using merge().