List of vectors in C++ STL with examples
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. For implementing a singly linked list, we use a forward list.
Functions used with List:
- push_front(x): Adds a new element ‘x’ at the beginning of the list.
- push_back(x): Adds a new element ‘x’ at the end of the list.
Forward list in STL implements singly linked list. Introduced from C++11, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only the next element while the list keeps track of both the next and previous elements, thus increasing the storage space required to store each element. The drawback of a forward list is that it cannot be iterated backward and its individual elements cannot be accessed directly.
Forward List is preferred over the list when only forward traversal is required (same as singly linked list is preferred over doubly linked list) as we can save space. Some example cases are, chaining in hashing, adjacency list representation of the graph, etc.
Functions used with Forward List:
- push_front(x):– Adds a new element ‘x’ at the beginning of the list.
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container.
Functions used with Vectors:
- size(): Returns the number of elements in the vector.
- push_back(): This function is used to push elements into a vector from the back.
A list of vectors can be quite useful while designing complex data structures. Each node can hold a vector.
Below is the implementation of the list of vectors:
[ 10 14 17 ] [ 2 6 11 ] [ 11 16 29 ]
Below is the implementation of forward list of vectors:
[ 11 16 29 ] [ 2 6 11 ] [ 10 14 17 ]
Please Login to comment...