×

C++ Multimap

Definition:

In C++, a multimap is similar to a map with the additional concept, where multiple elements possess the same keys. It is also not necessary that the key values and mapped values must be unique. The scenario is different in the case of multimaps. In a multimap, keys are always found in sorted order. This ordered property makes it difficult for competitive programmers to implement multimaps.

Moreover, multi maps are associative containers that are formed by combining key-value and mapped value, which is usually sorted or is in a specific order. Elements in multimap may sometimes have equivalent keys.

A multimap has key values, which are generally used to sort and uniquely identify elements, and the mapped values store the definitions or function related to this key. Some differences in the key and mapped value may exist, which later is grouped forming pairs by combining both.

Syntax

typedef pair<const Key, T> value_type;

Here,

     Key: It identifies each element by key value. Keys can be different.

     T: It identifies each element by mapped value. Mapped values may be different.

There are various functions associate with mulimaps. Some of them are as follows:

  1. begin() – It returns first element from the container while iteration.
  • end() – It returns the last element from the container while iteration.
  • size() – It returns the size or say number of elements present.
  • max_size() – It returns maximum number of elements an iterator can hold.
  • empty() – checks whether multimap is empty.
  • pair<int,int> insert(keyvalue,multimapvalue) – It is used to insert new elements in the multimap.

There are still plenty of such functios present the C++ STL . We may now see some basic coding examples and algorithms working behind it.

 #include <string.h>
 #include <iostream>
 #include <map>
 #include <utility>
 using namespace std;
 int main()
 {
    map<int, string> Professors;
    Professors[500] = "M. Chinnaswami";
    Professors[200] = "Venugopal Iyyer";
    Professors[350] = "Trichipalli Parampir";
    Professors[600] = "Mutthuswami Iyer";
    Professors[230] = "Rajshekhara Shriniwasana";
    cout << "Professors[500]=" << Professors[5000] << endl << endl;
    cout << "Size of the map: " << Professors.size() << endl;
    cout << endl << "Original Order:" << endl;
    for( map<int,string>::iterator ii=Professors.begin(); ii!=Professors.end(); ++ii)
    {
        cout << (*ii).first << ": " << (*ii).second << endl;
   }
    cout << endl << "Reversed order:" << endl;
    for(map<int,string>::reverse_iterator ii=Professors.rbegin(); ii!=Professors.rend(); ++ii)
   {
        cout << (*ii).first << ": " << (*ii).second << endl;
   }
 } 

Output:

C++ Multimap

Explanation:

The above code explains how to map the key values associated with multimap. In the above code, we have taken arguments in the two forms i.e. integer and string to assign keys of Professors. We can visualize the output. Once the mapped values are sorted in ascending order and later in descending order, it gives us the idea that the mapped and key values can highly be useful for the data present in the form of arrays where we want to find the redundant values associated with them.

Note: The defined map provides a comparison operator in the map declaration to order the indexes. It provides a default comparison for the data type. In the example above, we can see that the key type is an integer with (=) operator and (<) operator can easily operate.

Let’s us now take a straight forward look to the other functions present through the data table below.

        Functions          Descriptions
       constructorIt constructs multimap.
       destructorIt destroys/removes multimap.
Iterators (cbegin, cend, rbegin, rend,crbegin, crend)These functions manipulate the multimap using iterators from beginning to end and also in reversee order.
Capacity (empty, size and max_size)These functios check size, maximum size and elements present or not.
        Modifiers (erase, insert, clear, swap, emplace)These functions are used to erase, insert, remove or clear, exchange or insert new elements by hint.
Observers (key_comp, value_comp)Return copy of key comparison and value comparison.
       Allocator (get_allocator)Returns allocator used to construct the multimap.
      Operations (count, upper_bound,lower_bound, find, equal_range)Returns the element and the iterator with keys, counts, value of upper and lower bounds and matches elements with given key.

Advantages of using Multimap

The advantages are listed below:

  1. It is comfortable to run through a multimap with iterators rather than using nested for-loop for the map and vector case.
  • Once we had inserted a value into the multimap, we know that the iterator would remain valid until we remove it. This is a very strong property; we can't have it with the map of vectors.
  • The value once inserted into a multimap remains valid until we remove it which is an added advantage over preferring a map of vectors.
  • In multimap, to get elements of a key and map of vectors we simply use [] operator and can have a vector of elements.

Related Topics

C++ Iterators

What are iterators ? Iterators are among the four foundations of the C++ Standard Template Library, also known as the STL. The memory address of the STL container classes is pointed...

15 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

Substring in C++

A substring is a function in c++ that is imported from the string library. An element of a string is called a substring. A substring contains two parameters length and...

2 minutes read.

Find the Size of Array in C/C++ without using sizeof() function

We know that arrays in C/C++ are the most essential data structures as they have the ability to hold the data in a continuous manner line where the address of...

3 minutes read.

C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort The technique of merge sort is based on the strategy of divide and conquer. We divide the set of while data into smaller bits, arranged...

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

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

4 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

Print Table Using For-loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

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

Reserved Keywords in C++

What are reserved keywords in C++? There are a few keywords that cannot be used as identifiers as those words are reserved for some other purposes, such keywords are called reserved...

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

C++ Goto

In this article, we will discuss the C++ goto statement with its syntax, use, key features, key points, pseudo code, and examples. What is the goto statement in C++? In C++, the...

4 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

Queue in C++

What is Queue? As the name suggests, the queue is the type of data structure that follows the FIFO (First In - First Out) mechanism. In simple words, it is...

4 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

Boost split in C++ library

Boost::split in C++ library Boost offers strong tools for adding mature, well-tested libraries to the C++ standard library. The boost: split function, which is a component of the Boost string algorithm...

2 minutes read.