C++ map

Introduction

The map is an associative container that holds key-value pairs.

Keys are sorted and unique.

A map is also implemented as a balanced binary tree/graph.

So now, instead of one value per element, we have two.

To use a map, we need to include the header.

To define a map, we use the std::map<type1, type2> map_name syntax.

Here the type1 represents the type of the key, and type2 represents the type of a value.

To initialize a map of int char pairs, for example, we can write:

#include <map> 

int main() //from w  w w . ja v  a 2s . c o  m
{ 
    std::map<int, char> mymap = { {1, 'a'}, {2, 'b'}, {3,'z'} }; 
} 

In this example, integers are keys, and the characters are the values.




PreviousNext

Related