Build a custom Map using Header file in C++
Last Updated :
23 Jul, 2025
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. Maps are implemented by self-balancing search trees. In C++ STL it uses Red-Black Tree.
Here we are going to implement a custom Map class which has an integer value as the key and the value stored corresponding to any key is also of integer type.
We will implement it using the AVL tree. To implement the map, we will first create a header file which will incorporate the functionalities of a map class. Below is the basic structure of the Map class:
Structure of Map class:
The structure of the AVL tree depends upon the structure of the node:
- Each node has pointers for the left child, the right child, and the parent.
- Each node has three values first (which is the key), second (which is the value to the corresponding key) and depth (height of the subtree for the node).
- The map class also has a static value cnt which stores the number of elements present in the map and a static node root, which is the root of the tree.
Store this in a header file (say map.h)
C++
class Map {
static class Map* root;
// Number of elements in the map
static int cnt;
// Left child, right child and parent
Map *left, *right, *par;
// First is key, second is value
// and depth is height of the subtree
// for the given node
int first, second, depth;
};
Functions/Operations To Be Implemented Using Custom Map
We will cover the following functionalities and methods in our map:
- insert()
- find()
- update()
- accessing any key
- erase()
- count()
- size()
- empty()
- clear()
- iterate the map
The methods and functionalities are discussed below:
1. insert():
This method is used to insert a key-value pair in the map. There are two insert() methods used here.
One is made public and it takes two parameters:
- first - It is the key
- second - It is the respective value of the key
Syntax:
map.insert(first, second);
Below is the implementation of this method
C++
void insert(int first, int second)
{
Map* temp = iterator(first);
// If element doesnot exist already
if (temp == nullptr)
insert(first)->second = second;
// If element exists already update it
else
temp->second = second;
}
Time Complexity: O(logN) where N is the size of map
The other one is made private. This method is called inside the operator overloading function of [].
- It takes only one parameter: first (It is the key).
- Creates the new node with "first" as the key and returns the instance of the node.
Syntax:
map[first] = second;
Below is the implementation of this method:
C++
Map* insert(int first)
{
// Increase the number of elements
cnt++;
Map* newnode = create(first);
// If empty tree simply create the root
if (root == nullptr) {
root = newnode;
return root;
}
Map *temp = root, *prev = nullptr;
while (temp != nullptr) {
prev = temp;
if (first < temp->first)
temp = temp->left;
else if (first > temp->first)
temp = temp->right;
else {
free(newnode);
// If element already exists
// decrease the count
cnt--;
// If the key is found then it is
// returned by reference so that it is
// updatable
return temp;
}
}
if (first < prev->first)
prev->left = newnode;
else
prev->right = newnode;
newnode->par = prev;
// Once inserted Check and balance the tree
// at every node in path from "newnode" to "root"
balance(newnode);
// New object is inserted and returned to
// initialize in the main during assignment
return newnode;
}
int& operator[](int key) {
return insert(key)->second;
}
Time Complexity: O(logN) where N is the size of the map
2. find():
It is used to find an element. This is a public method. It takes one parameter: first (which is the key) and returns the reference associated with the key. Internally it calls the private method iterator() to find the key
Syntax:
map.find(first);
Below is the implementation of the method
C++
Map* iterator(int first)
{
Map* temp = root;
while (temp != nullptr && temp->first != first) {
if (first < temp->first) {
temp = temp->left;
}
else {
temp = temp->right;
}
}
return temp;
}
Map* find(int first) {
return iterator(first);
}
Time Complexity: O(logN) where N is the size of the map.
3. update():
This value is used to update the value associated with a key. This is a public method. It takes two parameters:
- first: It is the key to be found.
- second: It is the new value of the key.
The function calls the iterator() function to get the instance of the key and updates the value associated to that key. If no such key exists then no operation is performed.
Syntax:
map.update(first, second);
Below is the implementation of the method.
C++
void update(int first, int second)
{
Map* temp = iterator(first);
if (temp != nullptr) {
temp->second = second;
}
}
Time Complexity: O(logN) where N is the size of the map
4. Accessing any key:
Any value can be accessed using the subscript operator[]. The concept of method overloading is used to implement the functionality. It is a public method and the search() function is called inside the overloading function. It takes one parameter: first (it is the value of the key)
Syntax:
map[first];
Below is the implementation of the method.
C++
const Map* iterator(int first) const
{
Map* temp = root;
while (temp != nullptr
&& temp->first != first) {
if (first < temp->first)
temp = temp->left;
else
temp = temp->right;
}
return temp;
}
const int search(int first) const
{
const Map* temp = iterator(first);
// If element exists with the given key
// return its value
if (temp != nullptr)
return temp->second;
// If element doesn't exist
// return default value of 0
return 0;
}
const int operator[](int key) const
{
// Search method is also qualified with const
return search(key);
}
Time Complexity: O(logN) where N is the size of the map.
5. erase():
It deletes the node with the given key and replaces it with either its in-order predecessor or in-order successor. It is a public method. It takes one parameter: first (it is the key whose value needs to be deleted). At the end of the function, it calls balance() method on the parent of that node which replaced the deleted node to balance the AVL tree.
Syntax:
map.erase(first);
Below is the implementation of the method.
C++
void erase(int first, Map* temp = root)
{
Map* prev = 0;
cnt--;
while (temp != 0 && temp->first != first) {
prev = temp;
if (first < temp->first) {
temp = temp->left;
}
else if (first > temp->first) {
temp = temp->right;
}
}
if (temp == nullptr) {
cnt++;
return;
}
if (cnt == 0 && temp == root) {
free(temp);
root = nullptr;
return;
}
Map* l = inorderPredecessor(temp->left);
Map* r = inorderSuccessor(temp->right);
if (l == 0 && r == 0) {
if (prev == 0) {
root = 0;
}
else {
if (prev->left == temp) {
prev->left = 0;
}
else {
prev->right = 0;
}
free(temp);
balance(prev);
}
return;
}
Map* start;
if (l != 0) {
if (l == temp->left) {
l->right = temp->right;
if (l->right != 0) {
l->right->par = l;
}
start = l;
}
else {
if (l->left != 0) {
l->left->par = l->par;
}
start = l->par;
l->par->right = l->left;
l->right = temp->right;
l->par = 0;
if (l->right != 0) {
l->right->par = l;
}
l->left = temp->left;
temp->left->par = l;
}
if (prev == 0) {
root = l;
}
else {
if (prev->left == temp) {
prev->left = l;
l->par = prev;
}
else {
prev->right = l;
l->par = prev;
}
free(temp);
}
balance(start);
return;
}
else {
if (r == temp->right) {
r->left = temp->left;
if (r->left != 0) {
r->left->par = r;
}
start = r;
}
else {
if (r->right != 0) {
r->right->par = r->par;
}
start = r->par;
r->par->left = r->right;
r->left = temp->left;
r->par = 0;
if (r->left != 0) {
r->left->par = r;
}
r->right = temp->right;
temp->right->par = r;
}
if (prev == 0) {
root = r;
}
else {
if (prev->right == temp) {
prev->right = r;
r->par = prev;
}
else {
prev->left = r;
r->par = prev;
}
free(temp);
}
balance(start);
return;
}
}
Time Complexity: O(logN) where N is the size of the map.
6. count():
This method returns the count of a key in the map. This is a public method. It takes one parameter: first(which is the key of value whose count should be found). This method calls the iterator() method internally and if no node is found then count is 0. Otherwise, count returns 1.
Syntax:
map.count(first);
Below is the implementation of the method.
C++
int count(int first)
{
Map* temp = iterator(first);
// If key is found
if (temp != nullptr)
return 1;
// If key is not found
return 0;
}
Time Complexity: O(logN) where N is the size of the map.
7. size():
This method returns the size of the map. This is a public method. This method does not take any parameter.
Syntax:
map.size();
Below is the implementation of the method.
C++
int size(void) {
return cnt;
}
Time Complexity: O(1)
8. empty():
This method checks if the map is empty or not. This is a public method. It returns true if the map is empty, else false. This method does not take any parameter.
Syntax:
map.empty();
Below is the implementation of the method.
C++
bool empty(void)
{
if (root == 0)
return true;
return false;
}
Time Complexity: O(1)
9. clear():
This method is used to delete the whole map in. This is a public method. It does not take any parameter. It takes the erase() method internally.
Syntax:
map.clear();
Below is the implementation of the method.
C++
void clear(void)
{
while (root != nullptr) {
erase(root->first);
}
}
Time Complexity: O(N * logN) where N is the size of the map
10. iterate():
This method is used to traverse the whole map. This is a public method. It also does not take any parameter. The nodes are printed in the sorted manner of key.
Syntax:
map.iterate();
Below is the implementation of the method.
C++
void iterate(Map* head = root)
{
if (root == 0)
return;
if (head->left != 0) {
iterate(head->left);
}
cout << head->first << ' ';
if (head->right != 0) {
iterate(head->right);
}
}
Time Complexity: O(N) where N is the size of the map
Creation of Custom Map Header
C++
// map.h
// C++ Program to implement Map class(using AVL tree)
// This is a header file map.h and doesnot contain main()
#include <iostream>
using namespace std;
// Custom Map Class
class Map {
private:
Map* iterator(int first)
{
// A temporary variable created
// so that we do not
// lose the "root" of the tree
Map* temp = root;
// Stop only when either the key is found
// or we have gone further the leaf node
while (temp != nullptr &&
temp->first != first) {
// Go to left if key is less than
// the key of the traversed node
if (first < temp->first) {
temp = temp->left;
}
// Go to right otherwise
else {
temp = temp->right;
}
}
// If there doesn't exist any element
// with first as key, nullptr is returned
return temp;
}
// Returns the pointer to element
// whose key matches first.
// Specially created for search method
// (because search() is const qualified).
const Map* iterator(int first) const
{
Map* temp = root;
while (temp != nullptr
&& temp->first != first) {
if (first < temp->first) {
temp = temp->left;
}
else {
temp = temp->right;
}
}
return temp;
}
// The const property is used to keep the
// method compatible with the method "const
// int&[]operator(int) const"
// Since we are not allowed to change
// the class attributes in the method
// "const int&[]operator(int) const"
// we have to assure the compiler that
// method called(i.e "search") inside it
// doesn't change the attributes of class
const int search(int first) const
{
const Map* temp = iterator(first);
if (temp != nullptr) {
return temp->second;
}
return 0;
}
// Utility function to return the Map* object
// with its members initialized
// to default values except the key
Map* create(int first)
{
Map* newnode = (Map*)malloc(sizeof(Map));
newnode->first = first;
newnode->second = 0;
newnode->left = nullptr;
newnode->right = nullptr;
newnode->par = nullptr;
// Depth of a newnode shall be 1
// and not zero to differentiate
// between no child (which returns
// nullptr) and having child(returns 1)
newnode->depth = 1;
return newnode;
}
// All the rotation operation are performed
// about the node itself
// Performs all the linking done when there is
// clockwise rotation performed at node "x"
void right_rotation(Map* x)
{
Map* y = x->left;
x->left = y->right;
if (y->right != nullptr) {
y->right->par = x;
}
if (x->par != nullptr && x->par->right == x) {
x->par->right = y;
}
else if (x->par != nullptr && x->par->left == x) {
x->par->left = y;
}
y->par = x->par;
y->right = x;
x->par = y;
}
// Performs all the linking done when there is
// anti-clockwise rotation performed at node "x"
void left_rotation(Map* x)
{
Map* y = x->right;
x->right = y->left;
if (y->left != nullptr) {
y->left->par = x;
}
if (x->par != nullptr && x->par->left == x) {
x->par->left = y;
}
else if (x->par != nullptr && x->par->right == x) {
x->par->right = y;
}
y->par = x->par;
y->left = x;
x->par = y;
}
// Draw the initial and final graph of each
// case(take case where every node has two child)
// and update the nodes depth before any rotation
void helper(Map* node)
{
// If left skewed
if (depthf(node->left)
- depthf(node->right) > 1) {
// If "depth" of left subtree of
// left child of "node" is
// greater than right
// subtree of left child of "node"
if (depthf(node->left->left)
> depthf(node->left->right)) {
node->depth
= max(depthf(node->right) + 1,
depthf(node->left->right) + 1);
node->left->depth
= max(depthf(node->left->left) + 1,
depthf(node) + 1);
right_rotation(node);
}
// If "depth" of right subtree
// of left child of "node" is
// greater than
// left subtree of left child
else {
node->left->depth = max(
depthf(node->left->left) + 1,
depthf(node->left->right->left)
+ 1);
node->depth
= max(depthf(node->right) + 1,
depthf(node->left->right->right) + 1);
node->left->right->depth
= max(depthf(node) + 1,
depthf(node->left) + 1);
left_rotation(node->left);
right_rotation(node);
}
}
// If right skewed
else if (depthf(node->left)
- depthf(node->right) < -1) {
// If "depth" of right subtree of right
// child of "node" is greater than
// left subtree of right child
if (depthf(node->right->right)
> depthf(node->right->left)) {
node->depth
= max(depthf(node->left) + 1,
depthf(node->right->left) + 1);
node->right->depth
= max(depthf(node->right->right) + 1,
depthf(node) + 1);
left_rotation(node);
}
// If "depth" of left subtree
// of right child of "node" is
// greater than that of right
// subtree of right child of "node"
else {
node->right->depth = max(
depthf(node->right->right) + 1,
depthf(node->right->left->right) + 1);
node->depth = max(
depthf(node->left) + 1,
depthf(node->right->left->left) + 1);
node->right->left->depth
= max(depthf(node) + 1,
depthf(node->right) + 1);
right_rotation(node->right);
left_rotation(node);
}
}
}
// Balancing the tree about the "node"
void balance(Map* node)
{
while (node != root) {
int d = node->depth;
node = node->par;
if (node->depth < d + 1) {
node->depth = d + 1;
}
if (node == root
&& depthf(node->left)
- depthf(node->right) > 1) {
if (depthf(node->left->left)
> depthf(node->left->right)) {
root = node->left;
}
else {
root = node->left->right;
}
helper(node);
break;
}
else if (node == root
&& depthf(node->left)
- depthf(node->right)
< -1) {
if (depthf(node->right->right)
> depthf(node->right->left)) {
root = node->right;
}
else {
root = node->right->left;
}
helper(node);
break;
}
helper(node);
}
}
// Utility method to return the
// "depth" of the subtree at the "node"
int depthf(Map* node)
{
if (node == nullptr)
// If it is null node
return 0;
return node->depth;
}
// Function to insert a value in map
Map* insert(int first)
{
cnt++;
Map* newnode = create(first);
if (root == nullptr) {
root = newnode;
return root;
}
Map *temp = root, *prev = nullptr;
while (temp != nullptr) {
prev = temp;
if (first < temp->first) {
temp = temp->left;
}
else if (first > temp->first) {
temp = temp->right;
}
else {
free(newnode);
cnt--;
return temp;
}
}
if (first < prev->first) {
prev->left = newnode;
}
else {
prev->right = newnode;
}
newnode->par = prev;
balance(newnode);
return newnode;
}
// Returns the previous node in
// inorder traversal of the AVL Tree.
Map* inorderPredecessor(Map* head)
{
if (head == nullptr)
return head;
while (head->right != nullptr) {
head = head->right;
}
return head;
}
// Returns the next node in
// inorder traversal of the AVL Tree.
Map* inorderSuccessor(Map* head)
{
if (head == nullptr)
return head;
while (head->left != nullptr) {
head = head->left;
}
return head;
}
public:
// Root" is kept static because it's a class
// property and not an instance property
static class Map* root;
static int cnt;
// "first" is key and "second" is value
Map *left, *right, *par;
int first, second, depth;
// overloaded [] operator for assignment or
// inserting a key-value pairs in the map
// since it might change the members of
// the class therefore this is
// invoked when any assignment is done
int& operator[](int key) {
return insert(key)->second;
}
// Since we have two methods with
// the same name "[]operator(int)" and
// methods/functions cannot be
// distinguished by their return types
// it is mandatory to include a const
// qualifier at the end of any of the methods
// This method will be called from a const
// reference to the object of Map class
// It will not be called for assignment
// because it doesn't allow to change
// member variables
// We cannot make it return by reference
// because the variable "temp" returned
// by the "search" method is
// statically allocated and therefore
// it's been destroyed when it is called out
const int operator[](int key) const
{
return search(key);
}
// Count returns whether an element
// exists in the Map or not
int count(int first)
{
Map* temp = iterator(first);
if (temp != nullptr) {
return 1;
}
return 0;
}
// Returns number of elements in the map
int size(void) {
return cnt;
}
// Removes an element given its key
void erase(int first, Map* temp = root)
{
Map* prev = nullptr;
cnt--;
while (temp != nullptr &&
temp->first != first) {
prev = temp;
if (first < temp->first) {
temp = temp->left;
}
else if (first > temp->first) {
temp = temp->right;
}
}
if (temp == nullptr) {
cnt++;
return;
}
if (cnt == 0 && temp == root) {
free(temp);
root = nullptr;
return;
}
Map* l
= inorderPredecessor(temp->left);
Map* r
= inorderSuccessor(temp->right);
if (l == nullptr && r == nullptr) {
if (prev == nullptr) {
root = nullptr;
}
else {
if (prev->left == temp) {
prev->left = nullptr;
}
else {
prev->right = nullptr;
}
free(temp);
balance(prev);
}
return;
}
Map* start;
if (l != nullptr) {
if (l == temp->left) {
l->right = temp->right;
if (l->right != nullptr) {
l->right->par = l;
}
start = l;
}
else {
if (l->left != nullptr) {
l->left->par = l->par;
}
start = l->par;
l->par->right = l->left;
l->right = temp->right;
l->par = nullptr;
if (l->right != nullptr) {
l->right->par = l;
}
l->left = temp->left;
temp->left->par = l;
}
if (prev == nullptr) {
root = l;
}
else {
if (prev->left == temp) {
prev->left = l;
l->par = prev;
}
else {
prev->right = l;
l->par = prev;
}
free(temp);
}
balance(start);
return;
}
else {
if (r == temp->right) {
r->left = temp->left;
if (r->left != nullptr) {
r->left->par = r;
}
start = r;
}
else {
if (r->right != nullptr) {
r->right->par = r->par;
}
start = r->par;
r->par->left = r->right;
r->left = temp->left;
r->par = nullptr;
if (r->left != nullptr) {
r->left->par = r;
}
r->right = temp->right;
temp->right->par = r;
}
if (prev == nullptr) {
root = r;
}
else {
if (prev->right == temp) {
prev->right = r;
r->par = prev;
}
else {
prev->left = r;
r->par = prev;
}
free(temp);
}
balance(start);
return;
}
}
// Returns if the map is empty or not
bool empty(void)
{
if (root == nullptr)
return true;
return false;
}
// Given the key of an element it updates
// the value of the key
void update(int first, int second)
{
Map* temp = iterator(first);
if (temp != nullptr) {
temp->second = second;
}
}
// Deleting the root of
// the tree each time until the map
// is not empty
void clear(void)
{
while (root != nullptr) {
erase(root->first);
}
}
// Inorder traversal of the AVL tree
void iterate(Map* head = root)
{
if (root == nullptr)
return;
if (head->left != nullptr) {
iterate(head->left);
}
cout << head->first << ' ';
if (head->right != nullptr) {
iterate(head->right);
}
}
// Returns a pointer/iterator to the element
// whose key is first
Map* find(int first) {
return iterator(first);
}
// Overloaded insert method,
// takes two parameters - key and value
void insert(int first, int second)
{
Map* temp = iterator(first);
if (temp == nullptr) {
insert(first)->second = second;
}
else {
temp->second = second;
}
}
};
Map* Map::root = nullptr;
int Map::cnt = 0;
Now save it as a header file say map.h to include it in other codes and implement the functionalities.
How to Execute the built Custom Map
Mentioned below is the procedure to be followed for implementing the map:
- First create a header file for map (map.h)
- Then store the header in the same folder in which the files implementing the map are stored.
- Include the map header in the files which will implement the map class.
- Compile and run the files implementing map.
Examples to show the use of Custom Map
The following programmes demonstrate the execution for the Map class by creating its functionalities.
Example 1: Programs to demonstrate the use of insert(), accessing any key and update() methods:
C++
#include "map.h"
#include <iostream>
using namespace std;
int main()
{
Map map;
// 1st way of insertion
map[132] = 3;
map[34] = 5;
map[42] = -97;
map[22] = 10;
map[12] = 42;
// 2nd way of insertion
map.insert(-2,44);
map.insert(0,90);
// accessing elements
cout<<"Value at key 42 before updating = "
<<map[42]<<endl;
cout<<"Value at key -2 before updating = "
<<map[-2]<<endl;
cout<<"Value at key 12 before updating = "
<<map[12]<<endl;
// Updating value at key 42
map[42] = -32;
// Updating value at key -2
map.insert(-2,8);
// Updating value at key 12
map.update(12,444);
// accessing elements
cout<<"Value at key 42 after updating = "
<<map[42]<<endl;
cout<<"Value at key -2 after updating = "
<<map[-2]<<endl;
cout<<"Value at key 12 after updating = "
<<map[12]<<endl;
cout<<"Value at key 0 = "<<map[0]<<endl;
return 0;
}
Output:
Example 2: Programme to demonstrate the use of erase(), clear() and iterate() methods:
C++
#include "map.h"
#include <iostream>
using namespace std;
int main()
{
Map map;
map[132] = 3;
map[34] = 5;
map[42] = -97;
map[22] = 10;
map[12] = 42;
// Iterating the Map elements before erasing 22
map.iterate();
map.erase(22);
// Iterating the Map elements after erasing 22
map.iterate();
// Deleting the whole map
map.clear();
// Now since there are zero elements
// in the Map the output is blank
cout<<"\nElements in Map after clear operation: ";
map.iterate();
return 0;
}
Output:
Example 3: Programme to demonstrate the use of find(), count(), empty() and size() methods:
C++
#include "map.h"
#include <iostream>
using namespace std;
int main()
{
Map map;
map[132] = 3;
map[34] = 5;
map[42] = -97;
cout<<"Value at 132 before updating = "
<<map[132]<<endl;
// Find method returns pointer to element
// whose key matches given key
Map *it = map.find(132);
// Updating the value at key 132
it->second = 98;
cout<<"Value at 132 after updating = "
<<map[132]<<endl;
// Count of an element which is not present
// in the map is 0
cout<<"Count of 77 = "<<map.count(77)<<endl;
// Count of an element which is present
// in the map is 1
cout<<"Count of 34 = "<<map.count(34)<<endl;
// Size of map/number of elements in map
cout<<"Map size = "<<map.size()<<endl;
// Map is not empty therefore returned 0
cout<<"Is map empty: "<<map.empty()<<endl;
// Clearing the map
map.clear();
// Map is empty therefore return 1
cout<<"Is map empty: "<<map.empty()<<endl;
return 0;
}
Output:
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
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
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