×

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or removed. Key values can have their related values modified.

Several fundamental Map operations include

begin(): The first element of the map container is indicated by an iterator returned by the begin() function. The begin() function returns an iterator that moves back and forth between the container's first and second elements.

end(): The end() function returns an iterator pointing past the map container's final element. It cannot be de-referenced since it does not refer to a legitimate element; instead, the end() function produces a bidirectional iterator.

size(): To determine how many elements are present in the map, use the size() function.

max_size(): The maximum number of elements the map can hold is returned.

empty(): The map container's empty status is checked using the empty() function.s

pair insert(key-value, map value): The insert() built-in method in the C++ STL is used to add elements to the map container that match a specific key.

erase(iterator position): When an element needs to be removed from a container, the built-in C++ STL method erase() is utilised. Keys, items at any certain place, or a specific range can all be erased using this method.

clear(): The map container's size becomes 0 when all the items are removed using the clear() function.

Let us try to implement this map using a C++ program.

Implementation of the map

// Using the CPP Program, Map will show how it has been implemented.

#include <iostream>
#include <iterator>
#include <map>
using namespace std;
int main()
{
	// empty map container
	map<int, int> cmptn1;
	// Incorporate elements in a random order.
	cmptn1.insert(pair<int, int>(6, 50));
	cmptn1.insert(pair<int, int>(5, 60));
	cmptn1.insert(pair<int, int>(4, 30));
	cmptn1.insert(pair<int, int>(3, 20));
	cmptn1.insert(pair<int, int>(2, 40));
	cmptn1.insert(pair<int, int>(1, 40));
	cmptn1[7]=10;	// A different approach of adding values to maps
	// cmptn1 map printing
	map<int, int>::iterator itr;
	cout << "\n The cmptn1 map is: \n";
	cout << "\tKEY\tELEMENT\n";
	for (itr = cmptn1.begin(); itr != cmptn1.end(); ++itr) {
		cout << '\t' << itr->first << '\t' << itr->second
			<< '\n';
	}
	cout << endl;
	// Going to transfer the components from cmptn1 to cmptn2.
	map<int, int> cmptn2(cmptn1.begin(), cmptn1.end());
	// Print every element of the map gquiz2.
	cout << "\nThe cmptn2 map after"
		<< " assign from the cmptn1 is : \n";
	cout << "\tKEY\tELEMENT\n";
	for (itr = cmptn2.begin(); itr != cmptn2.end(); ++itr) {
		cout << '\t' << itr->first << '\t' << itr->second
			<< '\n';
	}
	cout << endl;
	// eliminate every element up to
	// element in cmptn2 with key=3
	cout << "\ncmptn2 after the removal of"
			" the elements less than the key=3 : \n";
	cout << "\tKEY\tELEMENT\n";
	cmptn2.erase(cmptn2.begin(), cmptn2.find(3));
	for (itr = cmptn2.begin(); itr != cmptn2.end(); ++itr) {
		cout << '\t' << itr->first << '\t' << itr->second
			<< '\n';
	}
	// with key = 4, eliminate all entries
	int num;
	num = cmptn2.erase(4);
	cout << "\ncmptn2.erase(4) : ";
	cout << num << " removed \n";
	cout << "\tKEY\tELEMENT\n";
	for (itr = cmptn2.begin(); itr != cmptn2.end(); ++itr) {
		cout << '\t' << itr->first << '\t' << itr->second
			<< '\n';
	}
	cout << endl;


	// the lower and higher bounds for the map cmptn1 key = 5
	cout << "cmptn1.lower_bound(5) : "
		<< "\tKEY = ";
	cout << cmptn1.lower_bound(5)->first << '\t';
	cout << "\tELEMENT = " << cmptn1.lower_bound(5)->second
		<< endl;
	cout << "cmptn1.upper_bound(5) : "
		<< "\tKEY = ";
	cout << cmptn1.upper_bound(5)->first << '\t';
	cout << "\tELEMENT = " << cmptn1.upper_bound(5)->second
		<< endl;
	return 0;
}

Output

How to implement map in C++

Other lists of map functions used for the implementation of map

map equal_range(): A pair of iterators are returned by the map::equal range() built-in function in the C++ STL. The pair designates the boundaries of a set that contains all the elements in the container with keys equal to k. The first iterator in the pair returned points to the element because the map container only includes unique keys, and the second iterator in the pair points to the key that follows after key K because the map container only contains unique keys. The range returned is of length 1, with both iterators pointing to an element that has a key designating the size of the map and elements as 0, and if there are no matches with key K and key K is greater than the largest key, the range returned is of length 1.

map rend(): provides a reverse iterator that leads to the hypothetical element that comes before the map's initial key-value pair.

map find(): If an iterator for the element in the map with the key-value pair "g" is found, it returns it; otherwise, it returns an iterator to the end.

map operator=: assigns a container's contents to another container, replacing the one it now has.


Related Topics

C++ vs C#

What exactly is C++ programming? Bjorne Stroustrup is the creator of the C++ programming language. His goal was to create a powerful object-oriented programming language with the capabilities of C. It...

4 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

C++ Aggregation

C++ Aggregation Definition: In C++, aggregation is a process in which one class (as an entity reference) defines another class. It provides another way to reuse the class. It represents...

4 minutes read.

Web Development in C++

Before learning above C++ web development, we need to learn about CGI What is CGI? CGI stands for common gateway interface. CGI is a standard that tells us how the exchange of...

4 minutes read.

Advantage and disadvantage friend function C++

Friend Function: - A friend function in C++ is a function that can access the private, protected, and public members of a class. In C++, a friend function is a function that...

2 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

10 Best C and C++ Books for Beginners & Advanced Programmers

If you want to become a skilled software developer, you should never stop learning, whether you're a working professional or a student. Why, therefore, only C or C++? The fundamental...

6 minutes read.

C++ Virtual Destructor

In C++, a destructor is a class member function that is used to free up space or remove an object of the class that has gone out of scope. The...

4 minutes read.

Virtual Function Vs Pure Virtual Function

Virtual activity is a member function defined in the foundation phase that can be redefined by acquired classes. Let's have a look at an example: #include <iostream>   #include <bits/stdc++.h> #include <stdlib> using namespace std;   class Base   {    ...

5 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

Vector in C++

Vector in C++ In today’s article, we will be learning all the things about vector in C++ and how vector is different form an array in C++. So basically, vector is very...

3 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

C++ OOPs Concept

The main goal of C ++ programming is to add the idea of ​​object orientation to the C programming language. Inheritance, data binding, polymorphism and other concepts are part of...

4 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.