c++ map basics..

MAP – KEY VALUE PAIR

Notes:

  • Maps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order.
  • In a map, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key.
  • Maps are typically implemented as binary search trees.
  • Maps keep value in order O(log n) and as such are slower than unordered_map which is o(1) lookup as in hashing.

Example:
map<string, int> Employees;

insert

Employees[“Charlie M.”]=3374;

Employees.insert(std::make_pair(“Peter Q.”, 5328));

size

Employees.size()

iterate

for (map<string, int>::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii)

{

cout<<(*ii).first<<“: “<<(*ii).second<<endl;

}

or,

cout << Employees[“Charlie M.”] << endl;

find (returns iterator)

map<const char*, int, ltstr>::iterator cur  = Employees.find(“june”);

if (cur  == Employees.end() )

std::cout << “not found”;

else

cout << “cur (in alphabetical order) is ” << (*cur).first << endl;

cur++;

cout << “cur next (in alphabetical order) is ” << (*cur).first << endl;

delete

mymap.erase (it);                   // erasing by iterator

mymap.erase (‘c’);                  // erasing by key

it=mymap.find (‘e’);

mymap.erase ( it, mymap.end() ); //range delete

custom comparison

    struct ltstr

    {

      bool operator()(const char* s1, const char* s2) const

      {

        return strcmp(s1, s2) < 0;

      }

    };

    map<const char*, int, ltstr> months;

Sample program

#include <iostream>

#include <utility>

#include <unordered_map>

using namespace std;

int main ()

{

unordered_map<char,int> mymap;

mymap.emplace(‘x’,100);
mymap.emplace(‘y’,200);
mymap.emplace(‘a’,100);
mymap.insert(make_pair(‘m’,100));

std::cout << “mymap contains:”;
for (auto& x: mymap)
std::cout << ” [” << x.first << ‘:’ << x.second << ‘]’;
std::cout << ‘\n’;

return 0;

}