C++ multiset Library - Default Constructor



Description

The multiset::multiset() default constructor in C++ STL creates an empty multiset having no elements in the container. By default, it initializes a comparison function (std::less) and a default allocator. The default constructor is used when you need an empty multiset and insert elements later in the container.

Syntax

Following is the syntax of multiset default constructor −

multiset(); //C++98

multiset(const Compare& comp = Compare(), 
         const Allocator& alloc = Allocator());  // C++98

multiset() noexcept(noexcept(Allocator())); //C++11

Return value

The default constructor does not return any value since it is a constructor.

Exceptions

It never throws exceptions in C++11 onwards when using the default allocator.

Time complexity

The time complexity of multiset default constructor is constant O(1).

Examples of multiset Default Constructor

The following examples demonstrate the usage of multiset default constructor:

Creating an Empty multiset

In this example, we are creating an empty multiset using the default constructor and then inserting elements into it using multiset::insert() function.

#include <iostream>
#include <set>
using namespace std;
void printMultiset(const multiset<int>& numbers) {
    for (auto it = numbers.begin(); it != numbers.end(); ++it)
        cout << " " << *it;
    cout << endl;
}
int main() {
    multiset<int> numbers;
    cout << "Initial size of multiset: " << numbers.size() 
         << endl;
    numbers.insert(50);
    numbers.insert(20);
    numbers.insert(30);
    numbers.insert(20);
    numbers.insert(10);
    cout << "Multiset elements after insertions:";
    printMultiset(numbers);
    cout << "Size after insertions: " << numbers.size() 
         << endl;
    return 0;
}

The output of the above code is given below −

Initial size of multiset: 0
Multiset elements after insertions: 10 20 20 30 50
Size after insertions: 5

Using Default Constructor with Duplicate Elements

Here is an example of using a default constructor to create an empty multiset and add duplicate elements in the container using insert() −

#include <iostream>
#include <set>
using namespace std;
int main() {
    multiset<char> letters;
    cout << "Is multiset empty? " 
         << (letters.empty() ? "Yes" : "No") << endl;
    letters.insert('A');
    letters.insert('B');
    letters.insert('A');
    letters.insert('C');
    letters.insert('B');
    letters.insert('A');
    cout << "Multiset elements:";
    for (const auto &letter : letters)
        cout << " " << letter;
    cout << "\nTotal elements: " << letters.size() << endl;
    cout << "Count of 'A': " << letters.count('A') << endl;
    return 0;
}

The output of the above code is given below −

Is multiset empty? Yes
Multiset elements: A A A B B C
Total elements: 6
Count of 'A': 3
multiset.htm
Advertisements