introduction

std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison function Compare.

Search, removal, and insertion operations have logarithmic complexity. Maps are usually implemented as red-black trees.

Template.

template<
    class Key,
    class T,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<std::pair<const Key, T>>
> class map;

Before Start🎞️


<aside> 📢 In the depending video above, we need to understand the red-black-tree algorithm.

</aside>

Basic Use

<aside> ⚠️ There is a different technique for using a map between all c++ standards.

</aside>

C++98

#include <iostream>
#include <map>
#include <string>

int main()
{
    std::map<int, int> m;
    m[1] = 1;
    m[2] = 2;
    m[3] = 3;
    m[4] = 4;
    m.insert(std::make_pair(5, 5));
    m.insert(std::make_pair(6, 6));

    std::map<int, int>::iterator it = m.begin();

    for (; it != m.end(); ++it)
    {
        std::cout << it->first << " " << it->second << std::endl;
    }
   std::cout << "m.size() = " << m.size() << std::endl;
    m.clear();
    std::cout << "after m.clear(), m.size() = " << m.size() << std::endl;
}
output
1 1
2 2
3 3
4 4
5 5
6 6
m.size() = 6
after m.clear(), m.size() = 0

Ok, why do I need to explain the difference between all versions? There is some tricky about it. If you noted the code above, I assign the map to the iterator before I add it to the loop.

std::map<int, int>::iterator it = m.begin();

I use an iterator to access maps on C++ standard 98 because I can't use auto.

C++ 11 and onwards.

#include <iostream>
#include <map>
#include <string>

int main()
{
    std::map<int, int> m = {{1, 2}, {3, 4}, {5, 6}};

    for (auto &i : m)
    {
        std::cout << i.first << " " << i.second << std::endl;
    }
}