Set vs Map in C++ STL

C++Server Side ProgrammingProgramming

Set is an abstract data type in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, but it is possible to remove and add the modified value of that element.

A Map is an associative container that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values.

So, it is clear from above that, set contains the only key, and map contains a value with the key, both should have unique and sorted value.

For unordered and unsorted elements there are unordered_set/unordered_map,multiset/multimap.

Example Code

 Live Demo

#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
   set<int> s; //initializing a empty set container
   set<int>::iterator it; //Initializing a set container as iterator
   s.insert(7); //inserting elements in the set container s
   s.insert(6);
   s.insert(1);
   s.insert(4);
   s.insert(2);
   s.insert(9);
   s.insert(10);
   cout << "Elements are in set:\n";
   for ( auto it : s)
      cout << it << " "; //printing elements of the set container
   return 0;
}

Output

1 2 4 6 7 9 10

Example Code

Live Demo

#include<iostream>
#include <bits/stdc++.h>
using namespace std;

int main()
{
   map<char, int> m;                     //initialize a map
   map<char, int>::iterator iter;       //initializing a map as iterator
   m.insert (pair<char, int>('a', 10)); //inserting values to the map
   m.insert (pair<char, int>('b', 20));

   cout << "Elements in map:\n";
   for (iter=m.begin();iter!=m.end();iter++)
   cout << "[ " << iter->first << ", "<< iter->second << "]\n"; //printing the values of the map
   return 0;
}

Output

Elements in map: 
[ a, 10] 
[ b, 20]
raja
Published on 02-Apr-2019 17:44:17
Advertisements