The C++ STL Cheat Sheet provides short and concise notes on Standard Template Library (STL) in C++. Designed for programmers that want to quickly go through key STL concepts, the STL cheatsheet covers the concepts such as vectors and other containers, iterators, functors, etc., with their syntax and example.

What is Standard Template Library(STL)?
The C++ Standard Template Library (STL) is a collection of generic class and function templates to provide some commonly used data structures and algorithms. It contains optimized and error-free code for useful containers such as vector, list, stack, queue, etc. It is a part of the standard library of C++ and
Components of STL
C++ STL provides various components to make programming easier and more efficient. These components can be divided into four categories:
- Containers
- Iterators
- Algorithms
- Functors
STL Containers
The STL containers are the template classes to implement useful data structures such as dynamic arrays, hashmaps, linked lists, trees, etc. These containers allow programmers to store and manipulate data.
The STL containers can also be divided into 4 parts which are:
- Sequential Containers
- Container Adapters
- Associative Containers
- Unordered Containers
1. Sequential Containers
The sequential containers implement the data structures with sequential access. These include:
- Vector
- List
- Deque
- Array
- Forward List
2. Container Adapters
The container adapters implement data structures like queues, stacks, etc by providing different interfaces for sequential containers. These include:
3. Associative Containers
The associative containers are used to store ordered data that can be quickly searched using their key value. These include:
4. Unordered Containers
The unordered containers are similar to associative containers except that they don't store sorted data but still provide quick search time using key-value pairs. They are:
- Unordered Set
- Unordered Multiset
- Unordered Map
- Unordered Multimap
Each container is defined inside its respective header file with the same name.
1.1 - STL Vector
The vector container provides a dynamic array. It is defined as std::vector class template inside <vector> header file.
Vector Declaration
vector <data_type> vector_name; // 1D Vector
vector < vector<data_type> > vector_name; // 2D Vector
std::vector Member Functions
S. No. | Function | Description | Time Complexity |
---|
1. | begin() | Returns an iterator to the first element. | O(1) |
---|
2. | end() | Returns an iterator to the theoretical element after the last element. | O(1) |
---|
3. | size() | Returns the number of elements present. | O(1) |
---|
4. | empty() | Returns true if the vector is empty, false otherwise. | O(1) |
---|
5. | at() | Return the element at a particular position. | O(1) |
---|
6. | assign() | Assign a new value to the vector elements. | O(n) |
---|
7. | push_back() | Adds an element to the back of the vector. | O(1) |
---|
8. | pop_back() | Removes an element from the end. | O(1) |
---|
9. | insert() | Insert an element at the specified position. | O(n) |
---|
10. | erase() | Delete the elements at a specified position or range. | O(n) |
---|
11. | clear() | Removes all elements. | O(n) |
---|
Example:
C++
// C++ program to illustrate the vector container
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// 1d vector with initialization list
vector<int> v1 = { 1, 2, 3, 4, 5 };
// 2d vector with size and element value initialization
vector<vector<int> > v2(3, vector<int>(3, 5));
// adding values using push_back()
v1.push_back(6);
// printing v1 using size()
cout << "v1: ";
for (int i = 0; i < v1.size(); i++) {
cout << v1[i] << " ";
}
cout << endl;
v1.erase(v1.begin() + 4);
// printing v1 using iterators
cout << "v1: ";
for (auto i = v1.begin(); i != v1.end(); i++) {
cout << *i << " ";
}
// printing v2 using range based for loop
cout << "v2:-" << endl;
for (auto i : v2) {
for (auto j : i) {
cout << j << " ";
}
cout << endl;
}
return 0;
}
Outputv1: 1 2 3 4 5 6
v1: 1 2 3 4 6 v2:-
5 5 5
5 5 5
5 5 5
1.2 - STL List
The list container implements the doubly linked list data structure. It is defined as std::list inside <list> header file.
List Declaration
list <data_type> list_name;
std::List Member Functions
S. No. | Function | Description | Time Complexity |
---|
1. | begin() | Return the iterator to the first element. | O(1) |
---|
2. | end() | Returns an iterator to the theoretical element after the last element. | O(1) |
---|
3. | size() | Returns the number of elements in the list. | O(1) |
---|
4. | push_back() | Adds one element at the end of the list. | O(1) |
---|
5. | pop_back() | Removes a single element from the end. | O(1) |
---|
6. | push_front() | Adds a single element to the front of the list. | O(1) |
---|
7. | pop_front() | Removes a single element from the front. | O(1) |
---|
8. | insert() | Inserts an element at the specified position. | O(n) |
---|
9. | erase() | Deletes the element at the given position. | O(n) |
---|
10. | remove() | Removes all the copies of the given elements from the list. | O(n) |
---|
Example
C++
// C++ Program to illustrate the list container
#include <iostream>
#include <list>
#include <vector>
using namespace std;
// driver code
int main()
{
// creating std::list object using initializer list
list<int> l1 = { 1, 5, 9, 1, 4, 6 };
// vector for initialization
vector<char> v = { 'G', 'e', 'e', 'k', 's' };
list<int> l2(v.begin(), v.end());
// printing first element
cout << "First element if l1: " << l1.front() << endl;
// adding element
l1.insert(l1.begin(), 5);
// deleting element
l1.erase(l1.begin());
// traversing and printing l1
cout << "l1: ";
for (auto i = l1.begin(); i != l1.end(); i++) {
cout << *i << " ";
}
cout << endl;
// traversing and printing l2
cout << "l2: ";
for (auto i : l2) {
cout << char(i);
}
cout << endl;
return 0;
}
OutputFirst element if l1: 1
l1: 1 5 9 1 4 6
l2: Geeks
1.3 - STL Deque
The deque implements the double-ended queue which follows the FIFO mode of operation but unlike the queue, the deque can grow and shrink from both ends. It is defined as std::deque inside the <deque> header file.
Deque Declaration
deque <data_type> dequeu_name;
std::deque Member Functions
S. No. | Function | Description | Time Complexity |
---|
1. | begin() | Returns iterator to the first element. | O(1) |
---|
2. | end() | Returns an iterator to the theoretical element after the last element. | O(1) |
---|
3. | at() | Access specified element. | O(1) |
---|
4. | [ ] | Access element at the given index. | O(1) |
---|
5. | front() | Returns the first element. | O(1) |
---|
6. | back() | Returns the last element. | O(1) |
---|
7. | size() | Returns the number of elements. | O(1) |
---|
8. | push_back() | Add the elements at the end. | O(1) |
---|
9. | pop_back() | Removes the elements from the end. | O(1) |
---|
10. | push_front() | Add the elements at the front. | O(1) |
---|
11. | pop_front() | Removes the element from the front. | O(1) |
---|
Example
C++
// C++ program to illustrate the deque
#include <deque>
#include <iostream>
using namespace std;
int main()
{
// creating a deque
deque<int> d = { 1, 2, 3, 4, 5 };
// removing two elements from the back and pushing them
// at the front
d.push_front(d.back());
d.pop_back();
d.push_front(d.back());
d.pop_back();
for (auto i : d) {
cout << i << " ";
}
return 0;
}
1.4 - STL Stack
The stack is a container adaptor that operates one LIFO principle. It is defined as std::stack in <stack> header file.
Stack Declaration
stack <data_type> stack_name;
std::stack Member Functions
S. No. | Function | Description | Time Complexity |
---|
1. | empty() | Returns true if the stack is empty, false otherwise. | O(1) |
---|
2. | size() | Returns the number of elements in the stack. | O(1) |
---|
3. | top() | Returns the top element. | O(1) |
---|
4. | push(g) | Push one element in the stack. | O(1) |
---|
5. | pop() | Removes one element from the stack. | O(1) |
---|
Example
C++
// C++ Program to illustrate the stack
#include <bits/stdc++.h>
using namespace std;
int main()
{
stack<int> s;
for (int i = 1; i <= 5; i++) {
s.push(i);
}
s.push(6);
// checking top element
cout << "s.top() = " << s.top() << endl;
// getting all the elements
cout << "s: ";
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
// size after popping all elements
cout << "Final Size: " << s.size();
return 0;
}
Outputs.top() = 6
s: 6 5 4 3 2 1 Final Size: 0
1.5 - STL Queue
The queue is a container adapter that uses the FIFO mode of operation where the most recently inserted element can be accessed at last. It is defined as the std::queue class template in the <queue> header file.
Queue Declaration
queue <data_type> queue_name;
std::queue Member Functions
S. No. | Function | Description | Time Complexity |
---|
1. | empty() | Returns true if the queue is empty, otherwise false. | O(1) |
---|
2. | size() | Returns the number of items in the queue. | O(1) |
---|
3. | front() | Returns the front element. | O(1) |
---|
4. | back() | Returns the element at the end. | O(1) |
---|
5. | push() | Add an item to the queue. | O(1) |
---|
6. | pop() | Removes an item from the queue. | O(1) |
---|
Example
C++
// C++ program to illustate the queue container
#include <iostream>
#include <queue>
using namespace std;
int main()
{
// creating queue
queue<int> q;
// pushing elements
for (int i = 1; i <= 5; i++) {
q.push(i);
}
q.push(6);
cout << "q.front() = " << q.front() << endl;
cout << "q.back() = " << q.back() << endl;
// printing queue by popping all elements
cout << "q: ";
int size = q.size();
for (int i = 0; i < size; i++) {
cout << q.front() << " ";
q.pop();
}
return 0;
}
Outputq.front() = 1
q.back() = 6
q: 1 2 3 4 5 6
1.6 - STL Set
The set is an associative container that stores unique values in sorted order, either ascending or descending. It generally implements a red-black tree as an underlying data structure. It is defined as std::set class template inside <set> header file.
Note: To store the multiple keys, we can use the multiset container.
Set Declaration
set <data_type> set_name;
std::set Member Functions
S. No. | Function | Description | Time Complexity |
---|
1. | begin() | Returns an iterator to the first element. | O(1) |
---|
2. | end() | Return an iterator to the last element. | O(1) |
---|
3. | size() | Returns the number of elements. | O(1) |
---|
4. | empty() | Checks if the container is empty. | O(1) |
---|
5. | insert() | Inserts a single element. | O(logn) |
---|
6. | erase() | Removes the given element. | O(logn) |
---|
7. | clear() | Removes all elements. | O(n) |
---|
8. | find() | Returns the pointer to the given element if present, otherwise, a pointer to the end. | O(logn) |
---|
Example
C++
// C++ program to illustrate set
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main()
{
// creating vector
vector<int> v = { 1, 5, 3, 4, 2 };
// creating set using vector v
set<int> s(v.begin(), v.end());
// finding 4
if (s.find(4) == s.end()) {
cout << "4 not found" << endl;
}
else {
cout << "4 found" << endl;
}
// adding 9
s.insert(9);
// printing set
cout << "s: ";
for (set<int>::iterator i = s.begin(); i != s.end();
i++) {
cout << *i << " ";
}
cout << endl;
return 0;
}
Output4 found
s: 1 2 3 4 5 9
1.7 - STL Map
Maps are associative containers used to store the key-value pairs where each key should be unique. It generally implements a red-black tree to store data in sorted order. It is defined as std::map inside the <map> header file.
Note: To store the multiple keys, we can use the multimap container.
Map Declaration
map <key_type, value_type> map_name;
std::map Member Functions
S. No. | Function | Description | Time Complexity |
---|
1. | begin() | Returns an iterator to the first element. | O(1) |
---|
2. | end() | Returns an iterator to the theoretical element that follows the last element | O(1) |
---|
3. | size() | Returns the number of elements in the map | O(1) |
---|
4. | insert() | Adds a new element to the map. | O(logn) |
---|
5. | erase(iterator) | Removes the element at the position pointed by the iterator. | O(logn) |
---|
6. | erase(key) | Removes the key and its value from the map. | O(logn) |
---|
7. | clear() | Removes all the elements from the map. | O(n) |
---|
8. | find(key) | Return iterator to the element with the given key if found, otherwise returns iterator to the end. | O(logn) |
---|
Example
C++
// C++ Program to illustrate the map container
#include <iostream>
#include <map>
using namespace std;
int main()
{
// creating std::map object
map<int, string> m;
// adding elements
m[1] = "ONE";
m[2] = "TWO";
m[3] = "THREE";
// checking size
cout << "Size of map m: " << m.size() << endl;
// inserting using insert pair
m.insert({ 4, "FOUR" });
// deleting key 2 with its value
m.erase(2);
// printing the map
cout << "Map:-" << endl;
for (auto i : m) {
cout << "Key: " << i.first << '\t';
cout << "Value: " << i.second << endl;
}
return 0;
}
OutputSize of map m: 3
Map:-
Key: 1 Value: ONE
Key: 3 Value: THREE
Key: 4 Value: FOUR
1.8 - STL Unordered_set
The unordered_set is the version of the set container where the data is not sorted but we can still perform a quick search. It is due to the fact that these unordered_sets are implemented using hash tables. It is defined as std::unordered_set inside the <unordered_set> header file.
Note: To store the multiple keys, we can use the unordered_multiset container.
unordered_set Declaration
unordered_set <data_type> set_name;
std::unordered_set Member Functions
S. No. | Functions | Description | Time Complexity |
---|
1. | begin() | Returns an iterator to the first element. | O(1) |
---|
2. | end() | Returns an iterator to the theoretical element that follows the last element | O(1) |
---|
3. | size() | Returns the number of elements. | O(1) |
---|
4. | empty() | Returns true if the unordered_set is empty, otherwise false. | O(1) |
---|
5. | insert() | Insert an item in the container. | O(1) |
---|
6. | erase() | Removes an element from the container. | O(1) |
---|
7. | find() | Returns the pointer to the given element if present, otherwise, a pointer to the end. | O(1) |
---|
Example
C++
// C++ Program to illustrate the unordered_set container
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
// creating an unordered_set object
unordered_set<int> us = { 1, 5, 2, 3, 4 };
// checking size
cout << "Size of us: " << us.size() << endl;
// inserting data
us.insert(7);
// finding some key
if (us.find(3) != us.end()) {
cout << "3 found!" << endl;
}
else {
cout << "3 not found" << endl;
}
// traversing unordered_set using iterators
cout << "us: ";
for (auto i = us.begin(); i != us.end(); i++) {
cout << *i << " ";
}
cout << endl;
return 0;
}
OutputSize of us: 5
3 found!
us: 7 4 1 5 2 3
1.9 - STL Unordered_map
Unordered_maps are stores the data in the form of key-value pairs. They implement the hash table so there is no particular order in which the data is stored. They are defined as std::unordered_map class template inside <unordered_map> header file.
Note: To store the multiple keys, we can use the unordered_multimap container.
unordered_map Declaration
unordered_map <key_type, value_type> map_name;
std::unordered_map Member Functions
S. No. | Function | Description | Time Complexity |
---|
1. | begin() | Returns an iterator to the first element. | O(1) |
---|
2. | end() | Returns an iterator to the theoretical element that follows the last element | O(1) |
---|
3. | size() | Returns the number of elements. | O(1) |
---|
4. | empty() | Returns true if the unordered_set is empty, otherwise false. | O(1) |
---|
5. | find() | Returns the pointer to the given element if present, otherwise, a pointer to the end. | O(1) |
---|
6. | bucket() | Returns the bucket number where the data is stored. | O(1) |
---|
7. | insert() | Insert an item in the container. | O(1) |
---|
8. | erase() | Removes an element from the container. | O(1) |
---|
Example
C++
// C++ program to illustrate the unordered_map container
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
// creating unordered_map object
unordered_map<int, string> umap;
// inserting key value pairs
umap[1] = "ONE";
umap[2] = "TWO";
umap[3] = "THREE";
umap.insert({ 4, "FOUR" });
// finding some key
if (umap.find(12) != umap.end()) {
cout << "Key 12 Found!" << endl;
}
else {
cout << "Key 12 Not Found!" << endl;
}
// traversing whole map at once using iterators
cout << "umap:--" << endl;
for (auto i = umap.begin(); i != umap.end(); i++) {
cout << "Key:" << i->first
<< "\tValue: " << i->second << endl;
}
return 0;
}
OutputKey 12 Not Found!
umap:--
Key:4 Value: FOUR
Key:3 Value: THREE
Key:2 Value: TWO
Key:1 Value: ONE
STL Iterators
Iterators are the objects used to iterate through the STL containers. They can be seen as pointers that are used to traverse and manipulate the data inside containers.
- Iterators are defined inside the <iterator> header file.
- Each container has its own iterators.
Iterators can be classified into 5 types which are:
STL Iterators1. Input Iterator
Input Iterators are used for single-pass input operations.
- They can only be used for accessing (read operations) not assigning.
- They cannot be decremented.
- An element can only be accessed once.
- They have limited capability and come lowest in the iterator hierarchy.
istream_iterator is an example of the input iterator.
2. Output Iterator
Output Iterators are used for single-pass output operations.
- They can only be used for assigning purposes (write operations).
- An element can only be accessed once.
- They cannot be decremented.
- They come lowest in the hierarchy along with the Input Iterators.
ostream_iterator is an example of the output iterator.
3. Forward Iterator
Forward iterators contain features of both input and output iterators along with:
- It can be used for both read and write operations.
- It cannot be decremented as it can move only in a single direction.
- It can only move sequentially i.e., one step at a time.
- It is in the upper hierarchy compared to both input and output iterators.
forward_list::iterator are examples of the forward iterators.
4. Bi-Directional Iterator
The bi-directional iterators have all the features of forward iterators along with:
- They can move in both forward and backward directions.
- They can be used for both read and write operations.
map::iterator, set::iterator, multiset::iterator, and multimap::iterators are some examples of input iterator.
5. Random Access Iterator
Random access iterators are the most powerful iterators.
- They contain features of all the other iterators.
- They can move in both forward and backward directions.
- Read and write operations can be performed.
- Can move to any point in the container i.e. random access.
vector::iterator and array::iterator are some examples.

STL Algorithms
Algorithms are set of generic and optimal implementations of some useful algorithms to make programming easier and more efficient.
- These algorithms work with STL containers and iterators.
- Algorithms are defined inside the <algorithm> header file.
- C++ STL contains around 114 Algorithms which are listed in the article - Algorithm Library in C++ STL
Some of the commonly used algorithms are:
1. Sort
The std::sort algorithm is used to sort data in any given order.
Syntax of std::sort
sort (beginIterator, endIterator);
sort (beginIterator, endIterator, comparator); // for custom comparator
Note: Iterators must be RandomAccessIterators.
Example
C++
// C++ program to demonstrate default behaviour of
// sort() in STL.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
/*Here we take two parameters, the beginning of the
array and the length n upto which we want the array to
be sorted*/
sort(arr, arr + n);
cout << "\nArray after sorting using "
"default sort is : \n";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
OutputArray after sorting using default sort is :
0 1 2 3 4 5 6 7 8 9
2. Copy
The std::copy method efficiently copies a range of elements to another container using its iterators.
Syntax of std::copy
copy (beginIterator, endIterator, destIterator);
Note: Iterators can be of InputIterator, OutputIterator or ForwardIterator.
Example
C++
// C++ Program to print vector using copy function and input
// and output stream iterators
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
using namespace std;
int main()
{
// creating vector
vector<int> v = { 1, 2, 3, 4, 5 };
// copying data to ostream
copy(v.begin(), v.end(),
ostream_iterator<int>(cout, " "));
return 0;
}
3. Max Element
The std::max_element implements an efficient algorithm to find the maximum element in the container. To find minimum element, use std::min_element.
Syntax of std::max_element
max_element (firstIterator, lastIterator);
Note: The iterators can be of type ForwardIterators.
Example
C++
// C++ program to demonstrate the use of std::max_element
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
// creating vector
vector<int> v = { 10, 88, 2, 9, 45, 82, 546, 42, 221 };
// Finding the maximum value between the first and the
// fourth element
auto max = max_element(begin(v), end(v));
cout << "Maximum Element: " << *max << "\n";
return 0;
}
OutputMaximum Element: 546
4. Find
The std::find function is used to find the element in the given range.
Syntax of std::find
find (firstIterator, lastIterator, value);
Note: The iterators can be of the type InputIterator, ForwardIterator.
Example
C++
// C++ program to illustrate the find()
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// creating vector
vector<int> v
= { 1, 8, 97, 3, 654, 132, 65, 4, 321, 5, 45 };
// finding 5
auto itr = find(v.begin(), v.end(), 5);
if (itr != v.end()) {
cout << *itr << " is found!" << endl;
}
else {
cout << "5 is not found!" << endl;
}
return 0;
}
5. For Each
The std::for_each algorithm applies the specified instruction to each of the elements in the given range.
Syntax of std::for_each
for_each (firstIterator, lastIterator, unaryFunction);
Note: The iterators can be of the type ForwardIterator, InputIterator.
Example
C++
// C++ program to print vector using for
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
// creating vector
vector<int> v = { 1, 2, 3, 4, 5 };
// adding 1 to each element
for_each(v.begin(), v.end(), [](int& i){
i = i + 1;
});
// printing vector
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
return 0;
}
STL Function Objects (Functors)
The Function Objects, also known as Functors, are the objects that behave like a function. It is due to the overloading of the ( ) parenthesis operator. The functors are defined inside the <functional> header file.
STL provides some predefined functors such as:
- equal_to
- not_equal_to
- greater
- less
- plus
- minus
Example
C++
// C++ program to illustrate some builtin functors
#include <functional>
#include <iostream>
using namespace std;
int main()
{
// creating objects
equal_to<int> eq;
not_equal_to<int> neq;
greater<int> gt;
less<int> ls;
plus<int> p;
minus<int> m;
// printing return values
cout << "Functors and their return value\n";
cout << boolalpha;
cout << "equal_to, (10,20): " << eq(10, 20) << endl;
cout << "greater, (10,20): " << gt(10, 20) << endl;
cout << "less, (10,20): " << ls(10, 20) << endl;
cout << "plus, (10,20): " << p(10, 20) << endl;
cout << "minus(10,20): " << m(10, 20) << endl;
return 0;
}
OutputFunctors and their return value
equal_to, (10,20): false
greater, (10,20): false
less, (10,20): true
plus, (10,20): 30
minus(10,20): -10
Similar Reads
C++ Programming Language C++ is a programming language known for its fast speed, low level memory management and is often taught as first programming language. Why Learn C++?C++ is often taught as a foundational language to aspiring programmers, but it is much more than that:C++ is used in making operating systems, embedded
5 min read
C++ Overview
Introduction to C++ Programming LanguageC++ is a general-purpose programming language that was developed by Bjarne Stroustrup as an enhancement of the C language to add object-oriented paradigm. It is considered as a middle-level language as it combines features of both high-level and low-level languages. It has high level language featur
3 min read
Features of C++C++ is a general-purpose programming language that was developed as an enhancement of the C language to include an object-oriented paradigm. It is an imperative and compiled language. C++ has a number of features, including:Object-Oriented ProgrammingMachine IndependentSimpleHigh-Level LanguagePopul
5 min read
History of C++The C++ language is an object-oriented programming language & is a combination of both low-level & high-level language - a Middle-Level Language. The programming language was created, designed & developed by a Danish Computer Scientist - Bjarne Stroustrup at Bell Telephone Laboratories (
7 min read
Interesting Facts about C++C++ is a general-purpose, object-oriented programming language. It supports generic programming and low-level memory manipulation. Bjarne Stroustrup (Bell Labs) in 1979, introduced the C-With-Classes, and in 1983 with the C++. Here are some awesome facts about C++ that may interest you: The name of
2 min read
Setting up C++ Development EnvironmentC++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. If you do not want to set up a local environment you can also use online IDEs for compiling your program.Using Online IDEIDE stands for an integrated development environment. IDE is a software application that provides facilities to
8 min read
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
C++ Basics
Understanding First C++ ProgramThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
C++ Basic SyntaxSyntax refers to the rules and regulations for writing statements in a programming language. They can also be viewed as the grammatical rules defining the structure of a programming language.The C++ language also has its syntax for the functionalities it provides. Different statements have different
4 min read
C++ CommentsComments in C++ are meant to explain the code as well as to make it more readable. Their purpose is to provide information about code lines. When testing alternative code, they can also be used to prevent execution of some part of the code. Programmers commonly use comments to document their work.Ex
3 min read
Tokens in CIn C programming, tokens are the smallest units in a program that have meaningful representations. Tokens are the building blocks of a C program, and they are recognized by the C compiler to form valid expressions and statements. Tokens can be classified into various categories, each with specific r
4 min read
C++ KeywordsKeywords are the reserved words that have special meanings in the C++ language. They are the words that have special meaning in the language. C++ uses keywords for a specifying the components of the language, such as void, int, public, etc. They can't be used for a variable name, function name or an
2 min read
Difference between Keyword and Identifier in CIn C, keywords and identifiers are basically the fundamental parts of the language used. Identifiers are the names that can be given to a variable, function or other entity while keywords are the reserved words that have predefined meaning in the language.The below table illustrates the primary diff
3 min read
C++ Variables and Constants
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Constants in CIn C programming, const is a keyword used to declare a variable as constant, meaning its value cannot be changed after it is initialized. It is mainly used to protect variables from being accidentally modified, making the program safer and easier to understand. These constants can be of various type
4 min read
Scope of Variables in C++In C++, the scope of a variable is the extent in the code upto which the variable can be accessed or worked with. It is the region of the program where the variable is accessible using the name it was declared with.Let's take a look at an example:C++#include <iostream> using namespace std; //
7 min read
Storage Classes in C++ with ExamplesC++ Storage Classes are used to describe the characteristics of a variable/function. It determines the lifetime, visibility, default value, and storage location which helps us to trace the existence of a particular variable during the runtime of a program. Storage class specifiers are used to specif
6 min read
Static Keyword in C++The static keyword in C++ has different meanings when used with different types. In this article, we will learn about the static keyword in C++ along with its various uses.In C++, a static keyword can be used in the following context:Table of ContentStatic Variables in a FunctionStatic Member Variab
5 min read
C++ Data Types and Literals
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
Literals in CIn C, Literals are the constant values that are assigned to the variables. Literals represent fixed values that cannot be modified. Literals contain memory but they do not have references as variables. Generally, both terms, constants, and literals are used interchangeably. For example, âconst int =
4 min read
Derived Data Types in C++The data types that are derived from the primitive or built-in datatypes are referred to as Derived Data Types. They are generally the data types that are created from the primitive data types and provide some additional functionality.In C++, there are four different derived data types:Table of Cont
4 min read
User Defined Data Types in C++User defined data types are those data types that are defined by the user himself. In C++, these data types allow programmers to extend the basic data types provided and create new types that are more suited to their specific needs. C++ supports 5 user-defined data types:Table of ContentClassStructu
4 min read
Data Type Ranges and Their Macros in C++Most of the times, in competitive programming, there is a need to assign the variable, the maximum or minimum value that data type can hold but remembering such a large and precise number comes out to be a difficult job. Therefore, C++ has certain macros to represent these numbers, so that these can
3 min read
C++ Type ModifiersIn C++, type modifiers are the keywords used to change or give extra meaning to already existing data types. It is added to primitive data types as a prefix to modify their size or range of data they can store.C++ have 4 type modifiers which are as follows:Table of Contentsigned Modifierunsigned Mod
4 min read
Type Conversion in C++Type conversion means converting one type of data to another compatible type such that it doesn't lose its meaning. It is essential for managing different data types in C++. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { // Two variables of different t
4 min read
Casting Operators in C++The casting operators is the modern C++ solution for converting one type of data safely to another type. This process is called typecasting where the type of the data is changed to another type either implicitly (by the compiler) or explicitly (by the programmer).Let's take a look at an example:C++#
5 min read
C++ Operators
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
C++ Arithmetic OperatorsArithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands (generally numeric values). An operand can be a variable or a value. For example, â+â is used for addition, '-' is used for subtraction, '*' is used for multiplication, etc. Let's take a look at an
4 min read
Unary Operators in CIn C programming, unary operators are operators that operate on a single operand. These operators are used to perform operations such as negation, incrementing or decrementing a variable, or checking the size of a variable. They provide a way to modify or manipulate the value of a single variable in
5 min read
Bitwise Operators in CIn C, bitwise operators are used to perform operations directly on the binary representations of numbers. These operators work by manipulating individual bits (0s and 1s) in a number.The following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are
6 min read
Assignment Operators in CIn C, assignment operators are used to assign values to variables. The left operand is the variable and the right operand is the value being assigned. The value on the right must match the data type of the variable otherwise, the compiler will raise an error.Let's take a look at an example:C#include
4 min read
C++ sizeof OperatorThe sizeof operator is a unary compile-time operator used to determine the size of variables, data types, and constants in bytes at compile time. It can also determine the size of classes, structures, and unions.Let's take a look at an example:C++#include <iostream> using namespace std; int ma
3 min read
Scope Resolution Operator in C++In C++, the scope resolution operator (::) is used to access the identifiers such as variable names and function names defined inside some other scope in the current scope. Let's take a look at an example:C++#include <iostream> int main() { // Accessing cout from std namespace using scope // r
4 min read
C++ Input/Output
Basic Input / Output in C++In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams.Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of bytes
5 min read
cin in C++In C++, cin is an object of istream class that is used to accept the input from the standard input stream i.e. stdin which is by default associated with keyboard. The extraction operator (>>) is used along with cin to extract the data from the object and insert it to the given variable.Let's t
4 min read
cout in C++In C++, cout is an object of the ostream class that is used to display output to the standard output device, usually the monitor. It is associated with the standard C output stream stdout. The insertion operator (<<) is used with cout to insert data into the output stream.Let's take a look at
2 min read
Standard Error Stream Object - cerr in C++The standard error stream in C++ is a special output stream used to display error messages or warnings. It is represented by std::cerr and sends messages to the screen, just like std:: cout . However, unlike std:: cout, it is unbuffered, meaning it shows messages immediately. This helps in debugging
2 min read
Manipulators in C++A manipulator is a special function in C++ that is used with input/output streams (like cin, cout ) to change the way data is shown or read.We can use manipulators when we want to :Format numbersSet precision (decimals)Align textChange number base (like decimal to hexadecimal)Control spacingThey are
4 min read
C++ Control Statements
Decision Making in C (if , if..else, Nested if, if-else-if )In C, programs can choose which part of the code to execute based on some condition. This ability is called decision making and the statements used for it are called conditional statements. These statements evaluate one or more conditions and make the decision whether to execute a block of code or n
7 min read
C++ if StatementThe C++ if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not executed based on a certain condition. Let's take a look at an example:C++#include <iostream> using namespace std; int main() { int
3 min read
C++ if else StatementThe if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false, it wonât. But what if we want to do something else if the condition is false. Here comes the C++ if else statement. We can use the else statement with if statement to exec
3 min read
C++ if else if LadderIn C++, the if-else-if ladder helps the user decide from among multiple options. The C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C++ else-if ladder is bypassed. I
3 min read
Switch Statement in C++In C++, the switch statement is a flow control statement that is used to execute the different blocks of statements based on the value of the given expression. It is a simpler alternative to the long if-else-if ladder.SyntaxC++switch (expression) { case value_1: // code to be executed. break; case v
5 min read
Jump statements in C++Jump statements are used to manipulate the flow of the program if some conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution of a function.In C++, there is four jump statement:Table of Contentcontinue Statementbreak Statementreturn Statementgoto S
4 min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 min read
for Loop in C++In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the given number of times. It is generally preferred over while and do-while loops in case the number of iterations is known beforehand.Let's take a look at an example:C++#include <bits/stdc++.h
6 min read
Range-Based for Loop in C++In C++, the range-based for loop introduced in C++ 11 is a version of for loop that is able to iterate over a range. This range can be anything that is iteratable, such as arrays, strings and STL containers. It provides a more readable and concise syntax compared to traditional for loops.Let's take
3 min read
C++ While LoopIn C++, the while loop is an entry-controlled loop that repeatedly executes a block of code as long as the given condition remains true. Unlike the for loop, while loop is used in situations where we do not know the exact number of iterations of the loop beforehand as the loop execution is terminate
3 min read
C++ do while LoopIn C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at least once and continues executing as long as a given condition remains true. Unlike the while loop, the do-while loop guarantees that the loop body will execute at least once, regardless of whether the
4 min read
C++ Functions
Functions in C++A Function is a reusable block of code designed to perform a specific task. It helps break large programs into smaller, logical parts. Functions make code cleaner, easier to understand, and more maintainable.Just like in other languages, C++ functions can take inputs (called parameters), execute a b
8 min read
return Statement in C++In C++, the return statement returns the flow of the execution to the function from where it is called. This statement does not mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops immediately and returns the control from where it was calle
4 min read
Parameter Passing Techniques in CIn C, passing values to a function means providing data to the function when it is called so that the function can use or manipulate that data. Here:Formal Parameters: Variables used in parameter list in a function declaration/definition as placeholders. Also called only parameters.Actual Parameters
3 min read
Difference Between Call by Value and Call by Reference in CFunctions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters.The following table lists the differences between the call-by-value and call-by-reference methods of parameter passing.Call By Valu
4 min read
Default Arguments in C++A default argument is a value provided for a parameter in a function declaration that is automatically assigned by the compiler if no value is provided for those parameters in function call. If the value is passed for it, the default value is overwritten by the passed value.Example:C++#include <i
5 min read
Inline Functions in C++In C++, inline functions provide a way to optimize the performance of the program by reducing the overhead related to a function call. When a function is specified as inline the whole code of the inline function is inserted or substituted at the point of its call during the compilation instead of us
6 min read
Lambda Expression in C++C++ 11 introduced lambda expressions to allow inline functions which can be used for short snippets of code that are not going to be reused. Therefore, they do not require a name. They are mostly used in STL algorithms as callback functions.Example:C++#include <iostream> using namespace std; i
4 min read
C++ Pointers and References
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
C++ PointersA pointer is a special variable that holds the memory address of another variable, rather than storing a direct value itself. Pointers allow programs to access and manipulate data in memory efficiently, making them a key feature for system-level programming and dynamic memory management. When we acc
8 min read
Dangling, Void , Null and Wild Pointers in CIn C programming pointers are used to manipulate memory addresses, to store the address of some variable or memory location. But certain situations and characteristics related to pointers become challenging in terms of memory safety and program behavior these include Dangling (when pointing to deall
6 min read
Applications of Pointers in CPointers in C are variables that are used to store the memory address of another variable. Pointers allow us to efficiently manage the memory and hence optimize our program. In this article, we will discuss some of the major applications of pointers in C. Prerequisite: Pointers in C. C Pointers Appl
4 min read
Understanding nullptr in C++Consider the following C++ program that shows problem with NULL (need of nullptr) CPP // C++ program to demonstrate problem with NULL #include <bits/stdc++.h> using namespace std; // function with integer argument void fun(int N) { cout << "fun(int)"; return;} // Overloaded fun
3 min read
References in C++In C++, a reference works as an alias for an existing variable, providing an alternative name for it and allowing you to work with the original data directly.Example:C++#include <iostream> using namespace std; int main() { int x = 10; // ref is a reference to x. int& ref = x; // printing v
5 min read
Can References Refer to Invalid Location in C++?Reference Variables: You can create a second name for a variable in C++, which you can use to read or edit the original data contained in that variable. While this may not sound appealing at first, declaring a reference and assigning it a variable allows you to treat the reference as if it were the
2 min read
Pointers vs References in C++Prerequisite: Pointers, References C and C++ support pointers, which is different from most other programming languages such as Java, Python, Ruby, Perl and PHP as they only support references. But interestingly, C++, along with pointers, also supports references. On the surface, both references and
5 min read
Passing By Pointer vs Passing By Reference in C++In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++?Let's first understand what Passing by Pointer and Passing by Reference in C++ mean:Passing by
5 min read
When do we pass arguments by pointer?In C, the pass-by pointer method allows users to pass the address of an argument to the function instead of the actual value. This allows programmers to change the actual data from the function and also improve the performance of the program. In C, variables are passed by pointer in the following ca
5 min read