Difference between std::set and std::list
Last Updated :
02 Nov, 2023
Set: Set is a type of associative container which stores elements in a sorted manner. All the elements of a set are unique and can not be modified but can be removed or inserted. It is a template of Standard Template Library or STL in C++.
Syntax:
set <data_type> s
Below is the program to illustrate the same:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
set< int > s;
s.insert(10);
s.insert(5);
s.insert(15);
s.insert(1);
s.insert(1);
cout << "Elements in set:\n" ;
for ( auto it : s)
cout << it << " " ;
return 0;
}
|
Output
Elements in set:
1 5 10 15
List: The list is a type of sequence container in which elements are stored in non-contiguous memory allocation. It is implemented as a doubly-linked list so it provides iteration in both directions.
Syntax:
list <data_type> l;
Below is the program to illustrate the same:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
list< int > l;
l.push_back(10);
l.push_back(15);
l.push_back(5);
l.push_back(1);
l.push_back(1);
l.push_back(10);
cout << "Elements in list:\n" ;
for ( auto it : l)
cout << it << " " ;
return 0;
}
|
Output
Elements in list:
10 15 5 1 1 10
Below is the tabular difference between the set and list:
As seen in the above codes, after inserting the values {10, 5, 15, 1, 1} in the set, the elements get sorted and duplicate is not stored in the set. Hence, it is unordered. But in the case of the list the elements are exactly stored in the order they were inserted and duplicate is also stored. Hence, it is ordered.
S.No. |
Set
|
List
|
1 |
Set is sorted and unordered |
The list is unsorted and ordered |
2 |
Insertion cannot be done at the desired position |
Insertion can be done at any position using the insert() function |
3 |
Takes logarithmic time for searching an element. |
Takes linear time for searching for an element. |
4 |
Elements are unique. |
May contain duplicate elements. |
5 |
Can contain only one null value. |
Can contain more than one null value. |
6 |
Insertion and deletion take logarithmic time. |
Insertion and deletion take constant time. |
7 |
Implemented in HashSet, LinkedHashSet, and TreeSet. |
Implemented in ArrayList and LinkedList. |
Share your thoughts in the comments
Please Login to comment...