tags:

views:

344

answers:

3

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

+3  A: 

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;
Daniel Earwicker
A: 

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.

Eric Petroelje
A: 

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.

Example

struct ltstr
{
  bool operator()(const char* s1, const char* s2) const
  {
    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;    
  ++next;
  --prev;
  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.

tdelev