Home » C++ » C++ Map Example

C++ Map Example

If your question is to get a value by key using a C++ map or C++ map to check if a key exists or find in a map in C++ then the following C++ map example will answer these questions.

What is Map in C++?

In C++, maps are associative containers for storing elements in a mapped manner. Each element has a mapped value and a key value. The key values of the two mapped values cannot be the same.

C++ Map Example

In the following C++ map example, it will find the Sriram key in the map contacts, and if it is found it will print the contact number value on the screen.

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

int main ( ) {

	map<string, long> contacts;

	contacts["Jegan"] = 123456789;
	contacts["Meena"] = 523456289;
	contacts["Nitesh"] = 623856729;
	contacts["Sriram"] = 993456789;

	auto pos = contacts.find( "Sriram" );

	if ( pos != contacts.end() )
		cout << pos->second << endl;

	return 0;
}

Output

993456789