Multiset of Tuples in C++ with Examples
What is a tuple?
A tuple in C++ is an object which binds a group of elements together. The elements can be similar as well as different data types. The elements of tuples are initialized as in the order in which they will be accessed.
tuple<data_type1, data_type2, dataType3, ….> myTuple
dataType1, dataType2, dataType3 . . . . are similar or dissimilar data types
Functions associated with a tuple:
1. make_tuple(): make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in the tuple.
myTuple = make_tuple(value1, value2, value3,….)
2. get(): get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element.
index is the index of the element we want to access in myTuple. Indexing in a tuple begins with zero.
What is a multiset?
A multiset is a type of associative container that is similar to a set but in the case of a multiset, all elements are necessary to be pairwise distinct. In simple words, there can be more than one element with the same value.
dataType is a data type.
Functions associated with multiset:
- begin(): Returns an iterator to the first element in the multiset.
- end(): Returns an iterator to the theoretical element that follows the last element in the multiset.
- size(): Returns the number of elements in the multiset.
- max_size(): Returns the maximum number of elements that the multiset can hold.
- empty(): Returns whether the multiset is empty.
A multiset of tuples can be quite useful when an algorithm requires a complex data structure. This article focuses on how to create a multiset of tuples in C++. Note that for simplicity a tuple of three elements is taken into consideration but a tuple can contain more or fewer elements also.
Multiset of tuples
A multiset of tuples is a multiset in which each of the elements is a tuple.
multiset<tuple<dataType1, dataType2, dataType3>> multisetOfTuples;
dataType1, dataType2, dataType3 are similar or dissimilar data types.
Example 1: Below is the C++ program to implement a multiset of tuples:
2 1 4
2 3 5
2 3 5
4 2 3
4 2 3
In the above output, there is a total of five tuples are present in the multiset out of which (2, 3, 5) and (4, 2, 3) occur twice. By default, tuples are arranged in non-descending order in the multiset and follow the below logic:
- In the multiset, if the first value of two tuples is equal then the second value of tuples is compared and if it is also equal then the third value is compared.
- But it is always possible to pass a comparator to a set.
Example 2: Below is the C++ program to demonstrate passing a comparator to the multiset which arranges a multiset of tuples elements in non-ascending order.
5 8 4
2 3 5
2 3 5
2 1 4
1 2 3
In the above output, elements in the multiset are arranged according to non-ascending order. The tuple with values (2, 3, 5) has two copies in the multiset.