×

Maps in C++

Maps:

Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the combination of the keys and mapped values.

In other words, maps are functions found in the Standard Template Library (STL) that store key-value pairs that are unique. It can also be inserted or deleted but the value cannot be altered although values associated with the keys can be modified.

Let's look at maps to see how they are created.

typedef pair<const Key, T> value_type;

Here,

     Key is the type of key and value is the type of value that needs to be assigned.

Note: The keys and values are always inserted as pairs. We simply cannot just enter a key or a value individually.

Syntax of map function:

 template<
     class Key,
     class T,
     class Compare = std::less<Key>,
     class Allocator = std::allocator<std::pair<const Key, T> >
 > class map; 

The above member functions can be grouped with the following definitions.

Member FunctionsDefinitions
key_type    Key
mapped_type    Map
value_typePair<const Key, T>
size_typeUnsigned integer(std::size_T)
key_compareFor comparing
allocator_typeallocator
pointerConst pointer
const iteratorConst<iterator>
reverse_iteratorReverse_iterator<iterator>
const reverse_iteratorReverse_iterator<const_iterator>

Let us now look at the programming examples for maps.

Example 1:

 #include<bits/stdc++.h>
 using namespace std;
 int main ()
 {
   map<char,int> first;
   first['K']=100;
   first['L']=200;
   first['M']=300;
   first['N']=400;
    map<char, int>::iterator i;
    for(i=first.begin(); i!=first.end(); ++i){
       cout << it->first << " => " << it->second << '\n';
  }
   return 0;
 } 

Output:

Maps in C++

Explanation:

In the above code depiction, we initialized the map function with the members of type character and integer since we are assigning character values with an integer. The function map consists of an iterator I, which iterates from start to end using the functions associated with begin() and end(). It later increments the value by 1. The output is is printed on the console.

Example 2:

 #include<bits/stdc++.h>
 int main()
 {
     std::map<std::string, int> planets;
     planets.insert(std::make_pair("Jupiter", 6));
     planets.insert(std::make_pair("Titan", 7));
     planets["Sun"] = 0;
     planets["Saturn"] = 5;
     std::map<std::string, int>::iterator it = planets.begin();
     while(it != planets.end())
 {
         std::cout<<it->first<<" :: "<<it->second<<std::endl;
         it++;
  }
     if(planets.insert(std::make_pair("Saturn", 5)).second == false)
     {
         std::cout<<"Element with key 'Saturn' already exists"<<std::endl;
     }
     if(planets.find("Sun") != planets.end())
         std::cout<<"word 'Sun' found"<<std::endl;
     if(planets.find("Pluto") == planets.end())
         std::cout<<"word 'Pluto' not present"<<std::endl;
     return 0;
 } 

Output:

Maps in C++

Explanation:

The above code is implemented just to showcase how maps work with strings. Here, we assigned our map function having arguments in the form of strings and also have key values of integers. Since we have already come across the fact that maps accept mapped values and keys in pairs, therefore each code is assigned to some values respective of their definition in the map function.

The function returns the values assigned with the respective functions that have their values already assigned. It returns false if they already exist or not present within the pair of occurrences.

Additional functions associated with Maps in STL

  1. begin() : Return first element to the iterator in maps.
  • end(): Return last element to the iterator in maps.
  • size(): gives the size of the elements present.
  • empty(): checks whether map is empty.
  • pair insert(key_value,map_value): used for adding value.
  • erase(): removes the elements which the iterators points.
  • clear(): cleans or removes all the elements from the maps.
  • operator[]: returns element with the key given.
  • at: retrieves the given element associated with key.
  1. cbegin(): returns constant iterator pointing first element.
  1. cend(): return constant iterator point last element.
  2. crbegin(): return constant reverse iterator pointing first element.
  3. crend(): return constant reverse iterator pointing last element.
  4. rbegin(): return reverse iterator pointing first element.
  5. rend(): return reverse iterator pointing last element.

Advantages of using Maps in C++

The advantages of using Maps in C++ are:

  • Lookup time
  • Well ordered
  • Insertion

Let’s discuss the above advantages in detail.

Lookup time:

If keys are known to fall in a narrow integer range, then an array (or preferably a vector) is ideal but using maps reduces the effort of fetching time to 0(1) complexity. A map lets you maintain reasonable lookup performance (O(log(n))). But only takes up 2 spots to store the memory.  A map allow us to maintain lookup in O(log(n)) complexity and also allow us to use any type of operator through arguments using templates. Also, it allows us to compare different keys. Thus, to lookup on maps of strings will let us map the values like -

map[“jJavaTpoint”]=5;

Well ordered:

Keys in maps are stored in proper order allowing us to iterate over all the items from beginning to end, in sorted key order. Although it can be done using dynamic arrays called vectors, but maps allow having arbitrary key types without defined ordering.

Insertion

Inserting any element in array/vector requires shifting all the elements to the left. In the case of dynamic arrays, we may need to resize the vector which consumes the entire memory for the array. Therefore, the time complexity is increased. A map has reasonable insertion time (O(log(n))).


Related Topics

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

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++ operator

In this article, we will discuss about the operators in C++ with their types and examples. An operator is specially a symbol that tells compiler to perform specific manipulation. C++ contains...

5 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Lexicographically Next Permutation in C++

In this tutorial, we'll look at how to use C++ to generate the lexicographically next permutation of a string. The lexicographically next permutation is the larger permutation. "ACB," for example,...

3 minutes read.

How to build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

Splitting a string in C++

Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that...

4 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

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

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Design Patterns in C++

A design pattern offers an all-encompassing, repeatable answer to the typical issues that arise in software design. Usually, the pattern demonstrates the connections and interactions between several classes or objects....

10 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

C++ If

C++ Control Statement C++ control statement or decision-making statement is used to control the flow of program statement according to condition applied. C++ if Control Statement An if control statement in C++ is used to...

2 minutes read.