Sign up ×

What is a Map? How would I create and use one in C++?

share|improve this question
Change Waht into What too.. – joe Jun 22 '09 at 13:13
It's a device for looking things up, ironically, a bit like Google... – anon Jun 22 '09 at 13:17

3 Answers 3

up vote 3 down vote accepted

If you mean std::map, it stores pairs of values. In each pair, the first value is called the key, and can be used to quickly look up the associated other value.

You can write:

std::map<std::string, int> ages;
ages["Fred"] = 52;
ages["Sue"] = 31;

std::cout << "Fred's age is " << ages["Fred"] << std::endl;
share|improve this answer

What is a map - it's a data structure that holds pairs of related values. Each pair consists of a key and a value. Every key in a map must be unique, but different keys can have the same values. Maps are often used for caching or implementing lookup tables, much like a dictionary (which is actually what maps are called in some languages).

As for how to implement a map in c++, short answer is - you don't. You use std::map or one of its variants.

share|improve this answer

Map is collection type end it is implemented in C++ in the STL (Standard Template Library) end here is the official explanation from the library documentation.

Map is a Sorted Associative Container that associates objects of type Key with objects of type Data. Map is a Pair Associative Container, meaning that its value type is pair. It is also a Unique Associative Container, meaning that no two elements have the same key. Map has the important property that inserting a new element into a map does not invalidate iterators that point to existing elements. Erasing an element from a map also does not invalidate any iterators, except, of course, for iterators that actually point to the element that is being erased.


struct ltstr
    return strcmp(s1, s2) < 0;

int main()
  map<const char*, int, ltstr> months;

  months["january"] = 31;
  months["february"] = 28;
  months["march"] = 31;
  months["april"] = 30;
  months["may"] = 31;
  months["june"] = 30;
  months["july"] = 31;
  months["august"] = 31;
  months["september"] = 30;
  months["october"] = 31;
  months["november"] = 30;
  months["december"] = 31;

  cout << "june -> " << months["june"] << endl;
  map<const char*, int, ltstr>::iterator cur  = months.find("june");
  map<const char*, int, ltstr>::iterator prev = cur;
  map<const char*, int, ltstr>::iterator next = cur;    
  cout << "Previous (in alphabetical order) is " << (*prev).first << endl;
  cout << "Next (in alphabetical order) is " << (*next).first << endl;

Here is the complete documentation of the Map type in STL.

I hope this help.

share|improve this answer

Your Answer


