Associative Containers

Plan to throw one (implementation) away; you will, anyhow. Fred Brooks

map

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

0 Comments


Definition

Map is an associative container that store the items by combination of key and values. The key value is unique and stored in sorted order.

Character

Store the key and value pair. The value can be duplicated.
The items in a map are always sorted by its key.
The value can be accessed based on the key value.
The map implemented as binary search trees.

source Code

								
#include "stdafx.h"

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

class ComplexNumber
{
	friend ostream &operator << (ostream &, const ComplexNumber &);

public:
	int x;
	int y;

	ComplexNumber();
	ComplexNumber(const ComplexNumber &);
	~ComplexNumber(){};
	ComplexNumber &operator=(const ComplexNumber &rhs);
	int operator==(const ComplexNumber &rhs) const;
	int operator < (const ComplexNumber &rhs) const;
};

ComplexNumber::ComplexNumber()  
{
	x = 0;
	y = 0;
	
}

ComplexNumber::ComplexNumber(const ComplexNumber ©in)   
{
	x = copyin.x;
	y = copyin.y;
	
}

ostream &operator << (ostream &output, const ComplexNumber &ComplexNumber)
{
	output << ComplexNumber.x << ' ' << ComplexNumber.y <<  endl;
	return output;
}

ComplexNumber& ComplexNumber::operator=(const ComplexNumber &rhs)
{
	this->x = rhs.x;
	this->y = rhs.y;
	
	return *this;
}

int ComplexNumber::operator==(const ComplexNumber &rhs) const
{
	if (this->x != rhs.x) return 0;
	if (this->y != rhs.y) return 0;
	
	return 1;
}

int ComplexNumber::operator < (const ComplexNumber &rhs) const
{
	if (this->x == rhs.x && this->y == rhs.y ) return 1;
	if (this->x == rhs.x && this->y < rhs.y) return 1;
	if (this->x < rhs.x) return 1;
	return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
	cout << "Create map with string and ComplexNumber objects" << endl;
	map < string, ComplexNumber > M;
	ComplexNumber Ablob;

	Ablob.x = 7;
	Ablob.y = 2;
	
	M["1"] = Ablob;

	Ablob.x = 5;
	M["2"] = Ablob;

	
	M["3"] = Ablob;

	Ablob.x = 3;
	Ablob.y = 7;
	
	M["4"] = Ablob;

	cout << endl << "Display map items:" << endl;
	for (map < string, ComplexNumber>::iterator ii = M.begin(); ii != M.end(); ++ii)
	{
		cout << (*ii).first.c_str() << ": " << (*ii).second << endl;
	}


	return 0;
}

						

Output

    					 
					Create map with string and Complex Number objects

					Display map items:
					1: 7 2

					2: 5 2

					3: 5 2

					4: 3 7

					    					 
					    

When to use

When you want to use key and value pair, you can use map.

0 Comments



Please login to add comments.