×

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

Palindrome using Do-while loop in C++

What is Palindrome? A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++...

5 minutes read.

Difference between "int main( ) and int main(void)" in C/C++

int main( ) function In the C/C++ programming language, int main() indicates a function that returns an integer at the end of the program execution. In general, a value of '0' indicates...

3 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

C++ Prime number program

In this lesson, you'll learn how to verify whether a given number is a prime number or not in C++, and you'll obtain code to do it. What is the definition...

3 minutes read.

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

How to run program in turbo c++

What is Turbo C++? Turbo c++ is an integrated development environment (IDE) and a compiler to run C++ code. Turbo c++ helps to link the header files with the main code....

2 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.

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.

wcscpy(), wcslen(), wcscmp() Functions in C++

There are many built-in functions in C++ programming language which differentiate it from C programming language in most hardware-coded languages. We will now closely look into the applications of three...

4 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

C++ STL (Standard Template Library)

Introduction C++ is a flexible type and general proposed programming language. So we need a standard library that supports C++. C++ STL (Standard Template Library) is a collection of templates that...

6 minutes read.

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

How to create the Processes with Fork in C++

 In this article, we are going to explain the different methods that help us to create processes with a fork(). There are two methods to do so. These methods are...

2 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.