STL provides a range of data structures that are very useful in various scenarios. A lot of data structures are based on real-life applications. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized.
Most common Data Structures used are:
Containers or container classes store objects and data. There are in total seven standards “first-class” container classes and three container adaptor classes and only seven header files that provide access to these containers or container adaptors.
Note: We can include just one library, i.e., #include <bits/stdc++.h> that includes all the STL libraries but in certain competitions, including this library can make the code slow. To overcome this problem, we can add specific libraries to access particular data structures of STL. Also while removing the elements, it is required to take care if the data structure is empty or not. Calling remove function on an empty data structure leads to error. Below are the some Data Structures with their illustration shown
- Vector: The major problem while using arrays was that we had to specify size. This drawback was overcome by vectors. Vectors internally work as dynamically allocated arrays, which is the main reason as to how we can add elements without specifying the size of the vector. When the size of the vector becomes equal to capacity, the capacity of vector increases and thus we can add further elements.
Header file:
#include <vector>
Syntax:
vector<data type> variable_name;
Most common function for vector:
- push_back(): Used to push the element at the end of the vector. For faster method, use emplace_back().
- pop_back(): Used to remove the last element from the vector.
- size(): Returns the size of the vector.
- clear(): Deletes all the content of the vector.
- erase(): Deletes the specified index or data.
- empty(): Returns boolean value True if vector is empty, else returns False.
- Iterator lower_bound(Iterator first, Iterator last, const val): lower_bound returns an iterator pointing to the first element in the range [first, last) which has a value not less than ‘val’.
- Iterator upper_bound(Iterator first, Iterator last, const val): upper_bound returns an iterator pointing to the first element in the range [first, last) which has a value greater than ‘val’.
Below is the code to implement the above functions:
// C++ program to illustrate the// function of vector in C++#include <iostream>// Header file for vector if// <bits/stdc++.h> not included#include <vector>usingnamespacestd;// Function to print the vectorvoidprint(vector<int> vec){// vec.size() gives the size// of the vectorfor(inti = 0; i < vec.size(); i++) {cout << vec[i] <<" ";}cout << endl;}// Driver Codeintmain(){// Defining a vectorvector<int> vec;// Put all natural numbers// from 1 to 10 in vectorfor(inti = 1; i <= 10; i++) {vec.push_back(i);}cout <<"Initial vector: ";// print the vectorprint(vec);// Size of vectorcout <<"Vector size: "<< vec.size() <<"\n";// Check of vector is emptyif(vec.empty() ==false)cout <<"Is vector is"<<" empty: False\n";// Popping out 10 form the vectorvec.pop_back();cout <<"Vector after popping: ";print(vec);// Deleting the first element// from the vector using erase()vec.erase(vec.begin());cout <<"Vector after erase"<<" first element: ";print(vec);// Clear the vectorvec.clear();cout <<"Vector after "<<"clearing: None ";print(vec);// Check if vector is emptyif(vec.empty() ==true)cout <<"Is vector is"<<" empty: True\n";}chevron_rightfilter_noneOutput:Initial vector: 1 2 3 4 5 6 7 8 9 10
Vector size: 10
Is vector is empty: False
Vector after popping: 1 2 3 4 5 6 7 8 9
Vector after erase first element: 2 3 4 5 6 7 8 9
Vector after clearing: None
Is vector is empty: True -
Stack: It is Last In First Out (LIFO) data structure. It can be implemented using arrays, linked lists, and vectors. Some problems like reversing an element or string, parenthesis check, print next greater element, postfix expression, etc, can be done using stack class rather than making all the functions we can use its inbuilt functions.
Header file:
#include <stack>
Syntax:
stack<data_type> variable_name;
Most common function for stack:
- push(): Used to push the element at top of the stack.
- pop(): Deletes the top element of the stack but do not returns it.
- top(): Returns the top element of the stack.
- empty(): Return boolean value, ie, True if stack is empty, else returns false.
- size(): Returns the size of the stack.
Below is the code to implement the above functions:
// C++ program to illustrate the// function of stack in C++#include <iostream>// Header file for stack#include <stack>usingnamespacestd;// Function to print the stackvoidprint(stack<char> s){// Loops runs till stack// becomes emptywhile(s.empty() ==false) {// Prints the top elementcout << s.top() <<" ";// Now pops the same top elements.pop();}cout <<"\n";}// Driver Codeintmain(){// Given char arraychararray[]= {'G','E','E','K','S','F','O','R','G','E','E','K','S'};// Defining stackstack<char> s;// Check if stack is emptyif(s.empty() ==true) {cout <<"Stack is currently Empty"<<"\n";}else{cout <<"Stack is not empty"<<"\n";}// Push elements in stackfor(inti =sizeof(array) /sizeof(array[0]) - 1;i >= 0; i--) {s.push(array[i]);}// Size of stackcout <<"Size of stack: "<< s.size() <<"\n";// Content of stackcout <<"Stack initially: ";print(s);// Returning the top// element of the stackcout <<"Top element: "<< s.top() <<"\n";// Popping the top// element in stacks.pop();cout <<"Stack after 1"<<"pop operation: ";print(s);// Now checking the top elementcout <<"Top element after popping: "<< s.top() <<"\n";// Size of stackcout <<"Size of stack"<<"after popping: "<< s.size() <<"\n";// Again checking if the// stack is emptyif(s.empty() ==true) {cout <<"Stack is currently Empty"<<"\n";}else{cout <<"Stack is not empty"<<"\n";}return0;}chevron_rightfilter_noneOutput:Stack is currently Empty
Size of stack: 13
Stack initially: G E E K S F O R G E E K S
Top element: G
Stack after 1pop operation: E E K S F O R G E E K S
Top element after popping: E
Size of stackafter popping: 12
Stack is not empty -
Queue: It is First In First Out (FIFO) data structure.The reason why we require queues use a lot of practical application of first in first out and when data doesn’t need to be processed early. For example, in a queue for buying tickets for a show, the one who enters the queue first, get the ticket first. It can be implemented using arrays, linked lists, and vectors just like stacks. Some applications of queue include level-order traversal in trees and graphs, in resource sharing, etc.
Header file:#include <queue>
Sytax:
queue<Data Type> variable_name;
Most common function fo Queue:
- push(): Used to push the element at back of the queue
- pop(): Deletes the front element of the queue but does not return it.
- front(): Returns the front element of the queue, or the element that is first in the line.
- empty(): Return boolean value, ie, True if queue is empty, else returns false
- back(): Returns the last element of queue.
- size(): Returns the size of the queue.
Below is the code to implement the above functions:
// C++ program to illustrate the// function of vector in C++#include <iostream>// Header file for queue#include <queue>usingnamespacestd;// Function to print the queuevoidprint(queue<char> q){for(inti = 0; i < q.size(); i++) {// Printing the front elementcout << q.front() <<" ";// Popping the front elementq.pop();}cout <<"\n";}// Driver Codeintmain(){// Given arraychararray[]= {'G','E','E','K','S'};// Defining queuequeue<char> q;if(q.empty() ==true) {cout <<"Queue is empty\n";}for(inti = 0; i < 5; i++) {q.push(array[i]);}cout <<"Queue Initally: ";print(q);// Front elementcout <<"Front element: "<< q.front() <<"\n";// Back elementcout <<"Back Element: "<< q.back() <<"\n";// Size of queuecout <<"Size of queue: "<< q.size() <<"\n";// Emptyif(q.empty() ==false) {cout <<"Queue is not empty\n";}return0;}chevron_rightfilter_noneOutput:Queue is empty
Queue Initally: G E E
Front element: G
Back Element: S
Size of queue: 5
Queue is not empty -
Priority Queue: This data structure is similar to queues, but the order of first out is decided by a priority set by the user. The main functions include getting top priority element, insert, delete the top priority element or decrease the priority. Data structure Heaps is used and not BST, as in BST, creating trees is costly than heaps, and the complexity of heaps is better. Also, heaps provide Complete Binary Tree and Heap order property satisfying all the properties of Priority Queue. Priority Queue has 2 variations, Min Heap and Max Heap.
Complex problems like finding k largest or smallest elements, merge k unsorted arrays, Dijkstra’s Shortest Path Algorithm, Huffman code for compression, Prim’s Algorithm, etc. can be implemented easily.Header file:
#include <queue>
Syntax:
Min Priority Queue: priority_queue<Data Type> variable_name;
Max Priority Queue: priority_queue <Data Type, vector, greater> variable_name;Most common function fo priority queue:
- push(): Used to push the element in the queue
- pop(): Deletes the top priority element of the queue but does not return it. Deletes element with max priority in max heap else deletes min element
- size(): Returns the size of the queue.
- empty(): Returns boolean value, ie, true if queue is empty, else return false.
- top(): Returns the top element of the queue. In max priority queue, it returns the maximum, while in min priority queue, it returns the minimum value.
Below the use of above function:
// C++ program to illustrate the// function of priority queue in C++#include <iostream>// Header file for priority// queue, both MIN and MAX#include <queue>usingnamespacestd;// Function to print the// min priority queuevoidprint_min(priority_queue<int,vector<int>,greater<int> >q){while(q.empty() ==false) {// Print the front// element(MINIMUM)cout << q.top() <<" ";// Pop the minimumq.pop();}cout <<"\n";}// Function to print the// min priority queuevoidprint_max(priority_queue<int> q){while(q.empty() ==false) {// Print the front// element(MAXIMUM)cout << q.top() <<" ";// Pop the maximumq.pop();}cout <<"\n";}// Driver Codeintmain(){// MIN priority queuepriority_queue<int> max_pq;// MAX priority_queuepriority_queue<int, vector<int>,greater<int> >min_pq;// Is queue emptyif(min_pq.empty() ==true)cout <<"MIN priority "<<"queue is empty\n";if(max_pq.empty() ==true)cout <<"MAX priority"<<" queue is empty\n";cout <<"\n";for(inti = 1; i <= 10; i++) {min_pq.push(i);max_pq.push(i);}cout <<"MIN priority queue: ";print_min(min_pq);cout <<"MAX priority queue: ";print_max(max_pq);cout <<"\n";// Sizecout <<"Size of min pq: "<< min_pq.size() <<"\n";cout <<"Size of max pq: "<< max_pq.size() <<"\n";cout <<"\n";// Top elementcout <<"Top of min pq: "<< min_pq.top() <<"\n";cout <<"Top of max pq: "<< max_pq.top() <<"\n";cout <<"\n";// Pop the front elementmin_pq.pop();max_pq.pop();// Queus after poppingcout <<"MIN priority "<<"queue after pop: ";print_min(min_pq);cout <<"MAX priority "<<"queue after pop: ";print_max(max_pq);cout <<"\n";// Size after poppingcout <<"Size of min pq: "<< min_pq.size() <<"\n";cout <<"Size of max pq: "<< max_pq.size() <<"\n";cout <<"\n";// Is queue emptyif(min_pq.empty() ==false)cout <<"MIN priority "<<" queue is not empty\n";if(max_pq.empty() ==false)cout <<"MAX priority queue"<<" is not empty\n";}chevron_rightfilter_noneOutput:MIN priority queue is empty
MAX priority queue is emptyMIN priority queue: 1 2 3 4 5 6 7 8 9 10
MAX priority queue: 10 9 8 7 6 5 4 3 2 1Size of min pq: 10
Size of max pq: 10Top of min pq: 1
Top of max pq: 10MIN priority queue after pop: 2 3 4 5 6 7 8 9 10
MAX priority queue after pop: 9 8 7 6 5 4 3 2 1Size of min pq: 9
Size of max pq: 9
MIN priority queue is not empty
MAX priority queue is not empty -
Set: Sets are associative containers in which each element is unique. The elements cannot be modified once inserted in the set. A set ignores the duplicate values and all the elements are stored in sorted order. This data structure is particularly useful when incoming elements need to be sorted and modification is not required.
The sets can store elements in two orders, increasing order or decreasing order.
Header file:#include <set>
Syntax:
Increasing order: set<Data type> variable_name;
Decreasing order :set<Data type, greater<Data type> > variable_name;
Most common function fo Set:
- insert(): This function is used to insert a new element in the Set.
- begin(): This function returns an iterator to the first element in the set.
- end(): It returns an iterator to the theoretical element that follows the last element in the set.
- size(): Returns the total size of the set.
- find(): It returns an iterator to the searched element if present. If not, it gives an iterator to the end.
- count(): Returns the count of occurrences in a set. 1 if present, else 0.
- empty(): Returns boolean value, ie, true if empty else false.
Below is the code to implement the above functions:
// C++ program to illustrate functions// of set in C++#include <iostream>// Header file for set#include <set>usingnamespacestd;// Function to print the setvoidprint_min(set<int> s){cout <<"Min set: ";set<int>::iterator itr;for(itr = s.begin();itr != s.end(); ++itr) {cout << *itr <<" ";}cout << endl;}// Function to print the setvoidprint_max(set<int,greater<int> >s){cout <<"Max set: ";set<int, greater<int> >::iterator itr;for(itr = s.begin();itr != s.end(); ++itr) {cout << *itr <<" ";}cout << endl;}// Driver Codeintmain(){// Defining set stores values in// increasing orderset<int> min_set;// stores values in decreasing orderset<int, greater<int> > max_set;// Emptyif(min_set.empty() ==true) {cout <<"Min set is empty\n";}if(max_set.empty() ==true) {cout <<"Max set is empty\n";}cout << endl;// Inserting into the setfor(inti = 1; i <= 10; i++) {min_set.insert(i);max_set.insert(i);}// Printing the setprint_min(min_set);print_max(max_set);cout << endl;// Sizecout <<"Size of min set: "<< min_set.size() <<"\n";cout <<"Size of max set: "<< max_set.size() <<"\n";cout << endl;// Emptyif(min_set.empty() ==false) {cout <<"Min set is not empty\n";}if(max_set.empty() ==false) {cout <<"Max set is not empty\n";}cout << endl;}chevron_rightfilter_noneOutput:Min set is empty
Max set is empty
Min set: 1 2 3 4 5 6 7 8 9 10
Max set: 10 9 8 7 6 5 4 3 2 1Size of min set: 10
Size of max set: 10Min set is not empty
Max set is not empty -
List: Lists stores data in non-contiguous manner.Elements of the list can be scattered in the different chunks of memory.Access to any particular index becomes costly as traversal from know index to that particular index has to be done, hence it is slow than vector.Zero-sized lists are also valid.
Header file:#include <list>
Syntax:
list<Data Type> variable_name;
Most common function fo list:
- push_front(element): Inserts a new element ‘element’ at the beginning of the list .
- push_back(element) : Inserts a new element ‘element’ at the end of the list.
- pop_front(): Removes the first element of the list.
- pop_back(): Removes the last element of the list.
- front() : Returns the value of the first element in the list.
- back() : Returns the value of the last element in the list .
- empty(): Returns boolean value, ie, true if empty else false.
Below is the code to implement the above functions:
// C++ program to illustrate the above// functions in list#include <iostream>// Header file for lists#include <list>usingnamespacestd;// Function to print the listvoidprint(list<int> l){list<int>::iterator it;for(it = l.begin();it != l.end(); ++it)cout << *it <<" ";cout <<'\n';}// Driver Codeintmain(){// Defining integer listlist<int> l;// Pushing the elementsfor(inti = 0; i < 10; ++i) {l.push_back(i * 2);}// Printing the listcout <<"List initally is : ";print(l);// Front elementcout <<"Front element: "<< l.front() <<"\n";cout <<"List after Popping"<<" the front element: ";l.pop_front();print(l);// Last elementcout <<"Last element: "<< l.back() <<"\n";cout <<"List after Popping"<<" the last element: ";l.pop_back();print(l);// Reversing the listcout <<"Reverse the list: ";l.reverse();print(l);// Soring the listcout <<"Sort the list: ";l.sort();print(l);}chevron_rightfilter_noneOutput:
List initally is : 0 2 4 6 8 10 12 14 16 18
Front element: 0
List after Popping the front element: 2 4 6 8 10 12 14 16 18
Last element: 18
List after Popping the last element: 2 4 6 8 10 12 14 16
Reverse the list: 16 14 12 10 8 6 4 2
Sort the list: 2 4 6 8 10 12 14 16 -
Unordered Maps: Suppose you have a pencil box and some pens. You put some pens in the box, that would be random and not ordered unlike ordered maps but you can access any pen and work with it. The same is unordered maps, the elements are stored randomly but you can access any order anytime. The main difference is between ordered maps and unordered maps are the way the compiler stores them. It has two arguments, the first is called KEY, and the other is called Value. The keymaps to the value and is always unique.
Header file:
#include <unordered_map>
Syntax:
unordered_map<Data Type> variable name;
Most common function fo unordered map:
- count(): Returns boolean values, ie, 1 if the key passes exists, else false.
- erase(key) : Returns the passed key.
- clear() : Deletes the entire map.
- size() : Returns the size of the map.
Note: Unordered maps do not suppose pairs, ie, neither the key nor the value can have pair or similar data type/structure. In such cases, we need to explicitly create and define the required data structure to satisfy needs.
Below is the code for the above functions:
// C++ program to implement the above// functionalities in unordered_map#include <iostream>// Header file for unordered maps#include <unordered_map>usingnamespacestd;// Prints the mapvoidprint(unordered_map<int,int> m){for(autoi = m.begin();i != m.end(); i++) {std::cout << i->first<<" : "<< i->second <<'\n';}cout << endl;}// Driver Codeintmain(){// Defining unordered mapunordered_map<int,int> m;// Enters the soecified valuefor(inti = 0; i < 10; i++) {m[i] = 1;}// Print the mapcout <<"Map initially: \n";print(m);// Incresing value of// certain keys by 1for(inti = 0; i < 10; i += 4) {m[i] += 10;}// Print the mapcout <<"Map after increasing"<<" value: \n";print(m);// Sizecout <<"Size: "<< m.size()<<"\n";// count method to see if// 20 is present or notif(m.count(20) == 0) {cout <<"20 is not present"<<" in map\n";}// count method to see if 4// is present or notif(m.count(4) == 1) {cout <<"4 is not present in"<<" map with the value "<< m[4] <<"\n";}}chevron_rightfilter_noneOutput:
Map initially:
9 : 1
8 : 1
7 : 1
6 : 1
1 : 1
0 : 1
2 : 1
3 : 1
4 : 1
5 : 1Map after increasing value:
9 : 1
8 : 11
7 : 1
6 : 1
1 : 1
0 : 11
2 : 1
3 : 1
4 : 11
5 : 1Size: 10
20 is not present in map
4 is not present in map with the value 11 -
Ordered Maps: Suppose you have a new shelf in your room and some books. You arrange the books one after another but after arranging any number of books, you can access arranged books in any order and keep the book in the same place when you’ve read it. This is an example of a map. You fill the values one after another in order and the order is maintained always, but you can access any element anytime. This data structure is also implemented using dynamic arrays. Like unordered maps, it has two arguments, the first is called KEY, and the other is called Value. The keymaps to the value and is always unique.
Header file:
#include <ordered_map>
Syntax:
ordered_map<Data Type> variable name;
Most common function fo orderd map:
- count() : Returns boolean values, ie, 1 if the key passes exists, else false.
- erase(key): Returns the passed key.
- clear(): Deletes the entire map.
- size(): Returns the size of the map.
Note: Ordered maps do not suppose pairs, ie, neither the key nor the value can have pair or similar data type/structure. In such cases, we need to explicitly create and define the required data structure to satisfy needs.
Comparison between ordered and unordered maps can be found here. The difference is basically the time complexity as ordered maps have better time complexity in worse cases than unordered maps.
Below is the code for the above functions:
// C++ program to implement the above// functionalities in unordered_map#include <iostream>// Header file for ordered maps#include <map>usingnamespacestd;// Prints the mapvoidprint(map<int,int> m){for(autoi = m.begin();i != m.end(); i++) {std::cout << i->first<<" : "<< i->second <<'\n';}cout << endl;}// Driver Codeintmain(){// Defining ordered mapmap<int,int> m;// Enters the soecified valuefor(inti = 0; i < 10; i++) {m[i] = 1;}// Print the mapcout <<"Map initially: \n";print(m);// Incresing value of// certain keys by 1for(inti = 0; i < 10; i += 4) {m[i] += 10;}// Print the mapcout <<"Map after increasing value: \n";print(m);// Sizecout <<"Size: "<< m.size() <<"\n";// count method to see if 20// is present or notif(m.count(20) == 0) {cout <<"20 is not present in map\n";}// count method to see if 4// is present or notif(m.count(4) == 1) {cout <<"4 is not present in"<<" map with the value "<< m[4] <<"\n";}}chevron_rightfilter_noneOutput:Map initially:
0 : 1
1 : 1
2 : 1
3 : 1
4 : 1
5 : 1
6 : 1
7 : 1
8 : 1
9 : 1Map after increasing value:
0 : 11
1 : 1
2 : 1
3 : 1
4 : 11
5 : 1
6 : 1
7 : 1
8 : 11
9 : 1Size: 10
20 is not present in map
4 is not present in map with the value 11
Recommended Posts:
- Forward List in C++ | Set 1 (Introduction and Important Functions)
- Some important shortcuts in Competitive Programming
- Bits manipulation (Important tactics)
- Why Data Structures and Algorithms Are Important to Learn?
- Why is programming important for first year or school students?
- Total number of components in the index Array
- Number of connected components in a 2-D matrix of strings
- Sum of the minimum elements in all connected components of an undirected graph
- Largest subarray sum of all connected components in undirected graph
- Number of connected components in a doubly linked list
- Clone an undirected graph with multiple connected components
- Check if the length of all connected components is a Fibonacci number
- Program to count Number of connected components in an undirected graph
- Count of unique lengths of connected components for an undirected graph using STL
- Maximum sum of values of nodes among all connected components of an undirected graph
- Octal equivalents of connected components in Binary valued graph
- Maximum decimal equivalent possible among all connected components of a Binary Valued Graph
- C++ Mathematical Functions
- Inline Functions in C++
- List in C++ | Set 2 (Some Useful Functions)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



