Set of List and Forward List in C++ with examples
Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element.
Functions used with Sets:
- begin(): Returns an iterator to the first element in the set.
- end(): Returns an iterator to the theoretical element that follows the last element in the set.
- size(): Returns the number of elements in the set.
- max_size(): Returns the maximum number of elements that the set can hold.
- empty(): Returns whether the set is empty.
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 Lists:
- push_front(): This function is used to push elements into a list from the front.
- push_back(): This function is used to push elements into a list from the back.
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.
Functions used with Forward Lists:
- push_front(): This function is used to push elements into a Forward list from the front.
Sets of List in STL
A set of lists can be very useful in designing complex data structures.
set<list<data_type>> set_of_list: This stores lists. set<forward_list<data_type>> set_of_forward_list: This stores forward lists.
Below is the C++ program to demonstrate the implementation of set of lists:
[ 2 6 9 1 ] [ 2 6 9 11 ] [ 21 10 12 16 ]
Below is the C++ program to demonstrate the implementation of set of forward lists:
[ 2 11 9 6 ] [ 16 21 12 10 ]
By default, lists are arranged in non – descending order in the set and follow the logic that in the set, if the first value of two lists is equal then the second value of lists is compared, and so on.
Please Login to comment...