×

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

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

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.

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.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

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.

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.

Difference between exit() and _Exit() in C++

Before understanding the difference between the exit() and _Exit(), one must know about exit() and _Exit() functions. The exit() function in C/C++ The exit() method in the C language kills the calling...

3 minutes read.

C++ Reading file

In file handling, read() function is used to read data from the file into the program. The read() uses ifstream library to read data from a file. Syntax file-stream-class   file-stream-object;   file-stream-object.read((char *)&var , sizeof (var)); <h3">Example ofstream  outfile;         outfile . read((char*)&emp,sizeof(emp)); C++ File Handling read() Function Example Reading the content of existing...

2 minutes read.

Difference between OOP and POP in C++

Object-Oriented Programming (OOP) Prioritizes data over methods (functions) and treats data as an essential component of program development.  OOP prohibits the free flow of data throughout the system. Tighter ties to data manipulation...

4 minutes read.

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

Inheritance in C++ vs Java

Just like we inherit traits from our parents, object-oriented programming has a concept called inheritance. In terms of object-oriented programming, a class's traits and behaviours, or its data and methods,...

4 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

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

C++ STL Components

C++ STL Components In today’s article, we are going to learn about all the points things that is related to STL in C++ so stay connected because you are going to...

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

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.

fread() Function in C++ Programming

C++ language is used to make high-performance applications that can work efficiently, and it is one of the world's most popular languages. It is an object-oriented and high-level programming language;...

3 minutes read.

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows...

5 minutes read.

Bits stdc++.h in C++

<bits/stdc++.h> in C++ In essence, it is a header file that contains all the standard libraries. It makes sense to use this file in programming competitions to speed up work, especially...

2 minutes read.