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

hash_map

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

0 Comments


Definition

hash_map helps to store and retrieve the key and value pair elements. The elements are grouped into buckets based on the value of a hash function.

Character

It is not part of the C++ standard.
hash_map is the name of a hashed associative container in the Standard Template Library.
It store and retrieve the key and value pair elements.
MSDN recommends unordered_map Class instead of hash_map.

source Code

								
#include "stdafx.h"

#include < iostream >
#include < hash_map >
using namespace std;
using namespace stdext;


typedef pair < int, int > Int_Pair;


int _tmain(int argc, _TCHAR* argv[])
{
	hash_map < int, int > hm1;
	hash_map < int, int > ::iterator hm1_Iter;
	hash_map < int, int > ::const_iterator hm1_cIter;

	cout << "Insert items into hash map" << endl;
	for (int i = 0; i < 10;i++)
		hm1.insert(Int_Pair(i, i*2));

	hm1_cIter = hm1.begin();
	cout << "The first element of hash_map is " << hm1_cIter->first << "." << endl;

	cout << "Erase first element from hash_map " << endl;
	hm1_Iter = hm1.begin();
	hm1.erase(hm1_Iter);
	

	hm1_cIter = hm1.begin();
	cout << "The first element of hash_map is now " << hm1_cIter->first << "." << endl;

	cout << "Display all items from hash map " << endl;
	for (hm1_Iter = hm1.begin(); hm1_Iter != hm1.end(); hm1_Iter++)
		cout << "Key:" << hm1_Iter->first << " value:" << hm1_Iter->second << endl;
	cout << endl;

	return 0;
}

						

Output

    					 
					Insert items into hash map
					The first element of hash_map is 0.
					Erase first element from hash_map
					The first element of hash_map is now 8.
					Display all items from hash map
					Key:8 value:16
					Key:1 value:2
					Key:2 value:4
					Key:3 value:6
					Key:4 value:8
					Key:5 value:10
					Key:6 value:12
					Key:7 value:14
					Key:9 value:18
					    					 
					    

When to use

When you want store the key and value pair using hash functionality, you can use hash map.

0 Comments



Please login to add comments.