Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::set and std::multiset

In C++ by default both std::set and std::multiset have std::less<T> as their comparator. Can anyone please explain how does std::multiset allow duplicates and std::set does not?

like image 930
A Roy Avatar asked May 20 '15 02:05

A Roy


People also ask

What is the difference between std :: set and std :: multiset?

The essential difference between the set and the multiset is that in a set the keys must be unique, while a multiset permits duplicate keys.

What is the difference between set and multiset in C++?

In Set duplicate values are not allowed to get stored. On other hand in case of MultiSet we can store duplicate values. In 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.

Is multiset same set?

These objects are all different when viewed as multisets, although they are the same set, since they all consist of the same elements. As with sets, and in contrast to tuples, order does not matter in discriminating multisets, so {a, a, b} and {a, b, a} denote the same multiset.

What is the use of multiset in C++?

Multisets are a type of associative containers similar to the set, with the exception that multiple elements can have the same values. Some Basic Functions associated with multiset: begin() – Returns an iterator to the first element in the multiset –> O(1)


1 Answers

Both start with the equivalent an upper_bound on the existing contents to find the correct insertion point for the new item.

std::set then checks whether that found an existing item with a key equal to the new key, and if so returns, signaling failure.

std::multiset just inserts the new item at that point (and if it didn't return in the step above, std::set does the same).

like image 144
Jerry Coffin Avatar answered Sep 28 '22 08:09

Jerry Coffin