Unordered Collections

The trouble with programmers is that you can never tell what a programmer is doing until itís too late. Seymour Cray

unordered_map

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

0 Comments


Definition

Unordered maps are associative containers that store elements using key and value pair. The value retrieved based on the key.

Character

Map implemented using red-black tree. unordered_map implemented using hash-table.
Elements are not sorted.
Requires additional memory to keep the hash-table.
Order of elements in the controlled sequence depends on the hash function.

source Code

								
#include "stdafx.h"

#include < iostream >
#include < unordered_map >
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	cout << "Insert items into unordered_map " << endl;
	unordered_map < char, int > letter_counts{ { 'a', 27 }, { 'b', 3 }, { 'c', 1 } };

	cout << "Display items from unordered_map:" << endl;
	for (const auto &pair : letter_counts) {
		cout << "[" << pair.first << "]: " << pair.second << endl;
	}

	cout << endl;

	cout << "update [b] index with \'42\'" << endl;
	letter_counts['b'] = 42;  

	cout << "insert [x] index with \'9\'" << endl;
	letter_counts['x'] = 9;  

	cout << "Display items from unordered_map after modifications:" << endl;
	for (const auto &pair : letter_counts) {
		cout << "["<< pair.first << "]: " << pair.second << '\n';
	}

	return 0;
}

						

Output

    					 
					Insert items into unordered_map
					Display items from unordered_map:
					[a]: 27
					[b]: 3
					[c]: 1

					update [b] index with '42'
					insert [x] index with '9'
					Display items from unordered_map after modifications:
					[a]: 27
					[b]: 42
					[c]: 1
					[x]: 9
					    					 
					    

When to use

if you need pure lookup-retrieval, you can use unordered_map.

0 Comments



Please login to add comments.