Difference between Set and MultiSet in C++


In C++, both Set and MultiSet are the type of data structures which are used to store the data for easy accessing and insertion. On the basis of characteristics of both these data structures we can distinguish between Set and MultiSet.

Following are the important differences between Set and MultiSet −

Sr. No.KeySetMultiSet
1DefinitionSet in C++ can be defined as a type of associative container which stores the data in key value pair and in which each value element has to be unique, because the value of the element identifies it.On other hand MultiSet are part of the C++ STL (Standard Template Library) and are defined as the associative containers like Set that stores sorted key value pairs, but unlike Set which store only unique keys, MultiSet can have duplicate keys.
2SortingIn case of Set, data is stored in sorted order.In case of MultiSet also the data is stored in sorted order.
3Duplicate ValuesIn Set duplicate values are not allowed to get stored.On other hand in case of MultiSet we can store duplicate values.
4ManipulationIn case of Set, one cannot change the value once it gets inserted however we can delete or insert it again.However in case of MultiSet also we cannot change the value once get inserted.

Example

Set

#include
#include
using namespace std;
main() {
   int data[15] = {11, 55, 22, 66, 33, 22, 11, 44, 77, 88, 66, 99, 66, 23, 41};
   set my_set;
   for(int i = 0; i<15; i++) { my_set.insert(data[i]);
   }
   set::iterator it;
   for(it = my_set.begin(); it != my_set.end(); it++) {
      cout << "Item: " << *it << endl;
   }
}

Output

Item: 11
Item: 22
Item: 23
Item: 33
Item: 41
Item: 44
Item: 55
Item: 66
Item: 77
Item: 88
Item: 99

Example

MultiSet

#include
#include
using namespace std;
main() {
   int data[15] = {11, 55, 22, 66, 33, 22, 11, 44, 77, 88, 66, 99, 66, 23, 41};
   multiset my_set;
   for(int i = 0; i<15; i++) { my_set.insert(data[i]);
   }
   multiset::iterator it;
   for(it = my_set.begin(); it != my_set.end(); it++) {
      cout << "Item: " << *it << endl;
   }
}

Output

Item: 11
Item: 11
Item: 22
Item: 22
Item: 23
Item: 33
Item: 41
Item: 44
Item: 55
Item: 66
Item: 66
Item: 66
Item: 77
Item: 88
Item: 99

Updated on: 09-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements