×

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

How to improve programming skills in C++

Before getting started, one should know why to improve their programming skills. To become a good software developer or programmer, one must be skilled in at least one programming language. Many...

4 minutes read.

Palindrome using For loop in C++

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++ also allows...

6 minutes read.

C++ Namespaces

An Overview In each scope, a name can only represent one entity. As a result, there cannot be two independent variables with the similar names in the same scope, as this may cause...

10 minutes read.

C++ Program to find the element that occurs once

Write a program to find the element in the array that occurs once. Given that all the numbers in the array are present two times and the array is sorted,...

7 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

Memset in C++

Memset () is a function in the C++ programming language that fills memory blocks. The value of "ch" is first converted to an unsigned character. In this case, "ch" denotes the...

3 minutes read.

C++ String Concatenation

C++ String Concatenation In this section, we will learn about C ++ String Concatenation, what it does, how it works, and will also see its programs. What is the String Concatenation? The + operator...

3 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

Palindrome Using While Loop in C++

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++ also allows...

6 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

Computing index using Pointers Returned by STL Functions in C++

In this tutorial we will learn how to compute index using pointers which returned by STL functions in C++. Many built-in C++ functions return pointers to memory places that provide...

2 minutes read.

Virtual Functions and Runtime Polymorphism in C++

In this tutorial, we will explore more on virtual functions and runtime polymorphism in the most useful language C++. A virtual function is a member function with the keyword virtual used...

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++ Program to Implement Shell Sort

    C++ Program to Implement Shell Sort shell sort is basically an Insertion Sort variant. In the insertion sort, we only transfer elements ahead of one location. Many movements are involved...

2 minutes read.

RTTI (Run-Time Type Information) in C++

In C++, RTTI or Run-Time Type Information reveals information about the data type of an object at runtime and only works with classes that have at least one virtual function....

3 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.