In this article we will discuss how set and map are different and what factors we need to keep in mind while choosing right associative container.

Let’s start from set,

Set :

  • Set is an associative container which we need to store unique elements.
  • It always keeps the elements in sorted order.
  • Internally it maintains a balanced binary search tree of elements. Therefore when we search an element inside the set then it takes only log(n) complexity to search it.

Important Point about set – Once added then cannot change i.e.

Each element added inside the set is const i.e. you cannot modify that element, because if you could, then it would hamper set’s internal data structure i.e. it will lose its internal balanced binary search tree property and results in undefined behavior.

Let’s understand by example,

Create a set to store unique names of Departments and then try to change one,

In above example you cannot change the element through iterator because here our complete element which we have added in SET is a key and you cannot modify any key inside the SET.
But what if want to associate some Value with this key and want to change that associated value at run time. Then we need something other than SET and that’s it MAP.


  • Map is a associative container that is used to store key-value pair of elements with unique keys.
  • It always keeps the inserted pairs in sorted order based on the key.
  • Internally it maintains a balanced binary search tree to store keys. Therefore when searching key inside the map takes only log(n) complexity.
  • We cannot modify the key of any inserted pair in map.
  • We can modify the value associated with a key in any inserted pair in map.

Let’s understand by example,

Create a map of Departments and No of Employee count. Then search a Department and change its associated no of employee count.

When to choose SET and when MAP?

So, if you want to maintain a data structure of unique keys only without any associated value that plan to modify in future then use set. If you want to modify any element in set then erase it and then insert the new one.
Whereas, use map if you want to maintain a data structure of unique keys and some associated value with each key that you want to change in future.

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.