In this tutorial, we will discuss how to create & initialise a multiset in C++.
To use multiset, you need to include the ‘set’ header file i.e.
#include <set>
The syntax for creating a multiset object is as follows:
std::multiset<data_type> obj;
We need to specify the data type (data_type
) as a template parameter when declaring a multiset
object. This means that this multiset
can only hold elements of the specified data type.
For instance, one could create a multiset
of integers, like this,
std::multiset<int> numbers;
or a multiset
of strings, like this,
std::multiset<std::string> words;
This will establish an empty multiset of strings; there will be no elements in it.
You can also create and initialize a multiset in the same line. Like this,
// Create multiset and initialize with values std::multiset<int> numSet {11, 22, 33, 33, 33, 44, 33, 55};
For example, doing so with integers will initialize the multiset with 8 integer values. Internally, the multiset arranges the elements in a sorted order, which is ascending by default. We can verify this by iterating over all the elements in the multiset using a range-based for loop. In the example below, we’ll create a multiset of integers, initialize it using an initializer list, and then iterate over all the elements of the multiset, printing them to the console.
Let’s see the complete example,
#include <iostream> #include <set> int main() { // Create an empty multiset std::multiset<int> numbers; // Create multiset and initialize with values std::multiset<int> numSet {11, 22, 33, 33, 33, 44, 33, 55}; // Content of the multiset will be: // 11, 22, 33, 33, 33, 33, 44, 55 // Iterate over set and print elements for(const auto& elem : numSet) { std::cout<< elem<< ", "; } std::cout<<std::endl; }
Output
11, 22, 33, 33, 33, 33, 44, 55,
Summary
Today, we learned how to how to create & initialise a multiset in C++.