Associative Containers

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. Brian W. Kernighan

multimap

Language C++ | Level Intermediate | Category Standard Template Library (STL) | 2015-11-17 04:31:50

0 Comments


Definition

Multimap allows duplicate keys. Multimaps are associative container that store the elements with combination of keys and values with sorted order.

Character

Map store the key and value pair. The value can be duplicated.
Multimaps allow for multiple entries with the same key.
It sorted by its key values. It can sort according to the comparison function Compare.
it provides bidirectional iterators to access its elements

source Code

								
#include "stdafx.h"

#include < string.h >
#include < iostream >
#include < map >
#include < utility >
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{

	multimap < string, int > m;

	cout << "Create multimap and insert items " << endl;

	m.insert(pair < string, int > ("a", 1));
	m.insert(pair < string, int > ("c", 2));
	m.insert(pair < string, int > ("b", 3));
	m.insert(pair < string, int > ("b", 4));
	m.insert(pair < string, int > ("a", 5));
	m.insert(pair < string, int > ("b", 6));

	cout << "Number of elements with key a: " << m.count("a") << endl;
	cout << "Number of elements with key b: " << m.count("b") << endl;
	cout << "Number of elements with key c: " << m.count("c") << endl;

	cout << "Elements in mutimap: " << endl;
	for (multimap < string, int >::iterator it = m.begin();
		it != m.end();
		++it)
	{
		cout << "  [" << (*it).first.c_str() << ", " << (*it).second << "]" << endl;
	}

	m.clear();

	return 0;
}

						

Output

    					 
					Create multimap and insert items
					Number of elements with key a: 2
					Number of elements with key b: 3
					Number of elements with key c: 1
					Elements in mutimap:
					  [a, 1]
					  [a, 5]
					  [b, 3]
					  [b, 4]
					  [b, 6]
					  [c, 2]
					    					 
					    

When to use

Multimaps allow for multiple entries with the same key. When you want map functionality with multiple keys, you can use multi map.

0 Comments



Please login to add comments.