Skip to main content

C++ STL Map Container – std::map

In this tutorial you will learn about STL Map container in C++ i.e., std::map and all functions applicable on it.

Map is an associative container. Map satisfies the word “associative”. That means every value in map is associated with a key. All keys are unique. No two mapped values can have same key. The type of key and stored values may differ. All elements follow a strict order. When we insert element automatically stored in its correct position.

C++ STL Map

Iterators that can be applicable on map:

begin(): returns iterator to the beginning.

end(): returns iterator to the end of the map.

rbegin(): returns reverse iterator to reverse beginning.

rend(): returns reverse iterator to reverse end.

cbegin(): Returns constant iterator to the beginning.

cend(): Returns constant iterator to the end.

These iterators we can use in our programs.

First thing we need to include map header file. Which is #include<map>

Let see some functions associated with map:

Inserting element into map:

Whenever an element inserted into map, size of the map increases. Since map contains unique keys when we try to insert an element into map, it always checks whether any element already inserted or not with this same key value.

There are different ways we can insert elements into map.

Method 1: Insert directly by passing element and its corresponding key.

mapName.insert (pair <keydataType, value dataType> ( key, value ));

Method 2: Using iterator. This returns iterator at inserted position.

mapName.insert (iterator,  pair < keyDatatype, value datatype > (key value, data value));

Example program for inserting into map:

#include <iostream>
#include <map>
#include <iterator>

using namespace std;

int main(){
        map < int, int> mp1; // declaring map
        map < int, int> :: iterator it;
        
        // Inserting method 1:
        for (int i=0; i<5; i++) {
                mp1.insert (pair < int, int> (i, i*10));
        } 
        // Caution: If you give any constant in place of first argument in insert. Only the first value will be inserted. Remaining will be pushed out as duplicates.
        
        // inserting method 2:
        it= mp1.begin();
        mp1.insert(it, pair < int, int> (99, 99));
        // Even this was inserted at starting position, due to porperty of ordering of associative containers it sorted according to its key value and inserted at last position.
        
        it= mp1.end();
        mp1.insert(it, pair < int, int> (10, 10));
        
        // printing 
        for ( it= mp1.begin(); it!=mp1.end(); it++) {
                cout << it -> first; 
                cout << '\t';
                cout << it -> second;
                cout << endl;
        }
        
        return 0;
}

Output

0 0
1 10
2 20
3 30
4 40
10 10
99 99

Other modification functions on map:

erase(): We can remove single element or a range of elements. The effect on map is whenever a value deleted from map, its size get reduced.

swap(): swaps elements of map1 to map2 and map2 to map1. Here both map1 and map2 are need not be of same size.

clear(): removes all elements in the map. It results map of size 0.

Example program to show above function:

#include <iostream>
#include <map>
#include <iterator>

using namespace std;

int main(){
        map < int, int > mp1;
        map < int, int > mp2;
        map <int, int> :: iterator it;
        
        for (int i=0; i<5; i++){
        // inserting elements into map
                mp1.insert (pair <int, int> (i,i+10));
        }
        
        // deleting element pointed by iterator
        it = mp1.begin();
        mp1.erase(it); // key 0 deleted
        
        cout << "printing remaining elements after one erase operation" << endl;
        for ( it= mp1.begin(); it!=mp1.end(); it++) {
                cout << it -> first; 
                cout << '\t';
                cout << it -> second;
                cout << endl;
        }
        
        // erasing range of values
        it= mp1.begin();
        mp1.erase(it,mp1.end());
        // this will erase all map
        
        cout << "checking map empty or not" << endl;
        int chk= mp1.empty();
        if (chk==1 )
                cout << "map is empty" << endl;
        else
                cout << "map is not empty" << endl;
        
        for (int i=0; i<5; i++){
        // inserting elements into map1
                mp1.insert (pair <int, int> (i,i+10));
        } 
        
        for (int i=0; i<5; i++){
        // inserting elements into map2
                mp2.insert (pair <int, int> (i,i*10));
        }
        
        cout << "map1 elements before swap" << endl;
        for ( it= mp1.begin(); it!=mp1.end(); it++) {
                cout << it -> first; 
                cout << '\t';
                cout << it -> second;
                cout << endl;
        }
        
        cout << "map2 elements before swap" << endl;
        for ( it= mp2.begin(); it!=mp2.end(); it++) {
                cout << it -> first; 
                cout << '\t';
                cout << it -> second;
                cout << endl;
        }
        
        // doing swaping operation
        mp1.swap(mp2);
        cout << "map1 elements after swap" << endl;
        
        for ( it= mp1.begin(); it!=mp1.end(); it++) {
                cout << it -> first; 
                cout << '\t';
                cout << it -> second;
                cout << endl;
        }
        
        cout << "map2 elements after swap" << endl;
        for ( it= mp2.begin(); it!=mp2.end(); it++) {
                cout << it -> first; 
                cout << '\t';
                cout << it -> second;
                cout << endl;
        }
        
        cout << "applying clear operation" << endl;
        mp1.clear(); mp2.clear();
        chk= mp1.empty();
        
        if (chk == 1)
                cout << "map is empty by clear operation" << endl;
        else
                cout << "map is not empty";
        
        return 0;
}

Output

printing remaining elements after one erase operation
1 11
2 12
3 13
4 14
checking map empty or not
map is empty
map1 elements before swap
0 10
1 11
2 12
3 13
4 14
map2 elements before swap
0 0
1 10
2 20
3 30
4 40
map1 elements after swap
0 0
1 10
2 20
3 30
4 40
map2 elements after swap
0 10
1 11
2 12
3 13
4 14
applying clear operation
map is empty by clear operation

Functions related to capacity:

empty(): returns a Boolean value whether map is empty or not.

size(): returns the size of the map.

max_size(): returns the maximum size a map can have.

Example program to show above functions:

#include <iostream>
#include <map>
#include <iterator>

using namespace std;

int main(){
        map < int, int> mp1;
        map < int, int> :: iterator it;
        
        for(int i=0; i<5; i++) {
                mp1.insert (pair <int, int> (i, i*10 ));
        }
        
        int chk = mp1.empty();
        if (chk == 1)
                cout << " map is empty" << endl;
        else
                cout << "map contains some elements" << endl;
        
        cout << "size of the map is " ;
        cout << mp1.size() << endl;
        
        cout << "maximum size of the map is " ;
        cout << mp1.max_size() << endl; 
        
        return 0;
}

Output

map contains some elements
size of the map is 5
maximum size of the map is 461168601842738790

Comment below if you have queries or found any information incorrect in above tutorial for C++ STL Map container i.e. std::map.

The post C++ STL Map Container – std::map appeared first on The Crazy Programmer.



from The Crazy Programmer http://www.thecrazyprogrammer.com/2017/08/stl-map.html

Comments

Popular posts from this blog

dotnet sdk list and dotnet sdk latest

Can someone make .NET Core better with a simple global command? Fanie Reynders did and he did it in a simple and elegant way. I'm envious, in fact, because I spec'ed this exact thing out in a meeting a few months ago but I could have just done it like he did and I would have used fewer keystrokes! Last year when .NET Core was just getting started, there was a "DNVM" helper command that you could use to simplify dealing with multiple versions of the .NET SDK on one machine. Later, rather than 'switching global SDK versions,' switching was simplified to be handled on a folder by folder basis. That meant that if you had a project in a folder with no global.json that pinned the SDK version, your project would use the latest installed version. If you liked, you could create a global.json file and pin your project's folder to a specific version. Great, but I would constantly have to google to remember the format for the global.json file, and I'd constan...

15 Web Design Trends to Watch in 2018

The modern world is full of extraordinary things that influence our imagination and mood. Our soul needs a perfect atmosphere and impressive spots. To apply such things in practice, we have submitted the list of the web trends that deserve your attention. Robert frost design analysis will meet all your wishes and expectations. Image Source Web Design Trends to Watch in 2018 1. More Organic Shapes Until this year, web design, as well as mobile design, were based on the right-angled and sharp-edged shapes. However, it seems that this year will bring some significant changes in the field of web design. The recent trends will offer the absolute rounded corners. In addition, the web design of 2018 will make the real things look like the cartoonish ones. 2.   Bold Minimalism Although some of you may think that this web design trend will not attract the Internet users. Indeed, the notion of minimalism is often associated with boredom and dullness. However, in this case, bold ...

R vs Python for Machine Learning

There are so many things to learn before to choose which language is good for Machine Learning. We will discuss each and everything about R as well as Python and the situation or problem in which situation we have to use which language. Let’s start Python and R are the two most Commonly used Programming Languages for Machine Learning and because of the popularity of both the languages Novice or you can say fresher are getting confused, whether they should choose R or Python language to commence their career in the Machine learning domain. Don’t worry guys through this article we will discuss R vs Python for Machine Learning. So, without exaggerating this article let’s get started. We will start it from the very Basics things or definitions. R vs Python for Machine Learning Introduction R is a programming language made by statisticians and data miners for statistical analysis and graphics supported by R foundation for statistical computing. R also provides high-quality graphics and...