C++ multiset Library - emplace() Function



Description

The multiset::emplace() function in C++ STL is used to insert a new element into the multiset container. The insertion is in place insertion method, which means the element is inserted into a multiset without creating any temporary object like insert() function or without using any extra space.

The advantage of using emplace() function instead of insert() function is that it is an in place element insertion method that avoids copying or movement of elements.

Syntax

Following is the syntax of multiset::emplace() function −

multiset_name.emplace(args);

Parameters

args − It represents the element that you want to insert into the multiset.

Return value

It returns an iterator pointing to the new element inserted in the multiset container.

Exceptions

If an exception is thrown, the container remains unchanged.

Time complexity

The time complexity of multiset::emplace() function is O(log n).

Examples of multiset::emplace() Function

The following examples demonstrate the usage of multiset::emplace() function in multiset −

Emplacing Elements in a multiset

Below is an example to add an element to the multiset scores using the multiset::emplace() function −

#include <iostream>
#include <set>
using namespace std;

void printEle(const multiset<int> &scores) {
    for (auto it = scores.begin(); it != scores.end(); ++it)
        cout << " " << *it;
    cout << endl;
}

int main(){
    multiset<int> scores = {85, 92, 78};
    cout << "Multiset elements:";
    printEle(scores);

    auto itr = scores.emplace(95);
    cout << "Multiset elements after emplacing 95:";
    printEle(scores);
    cout << "Iterator points to: " << *itr << endl;

    return 0;
}

The output of the above code is given below −

Multiset elements: 78 85 92
Multiset elements after emplacing 95: 78 85 92 95
Iterator points to: 95

Emplacing Custom Objects in multiset

In this example, we have created a Student data type using struct with name and rollNo as its members. We are using the emplace() function for constructing the Student objects directly (i.e., in place) in the multiset container by passing name and rollNo.

#include <iostream>
#include <set>
#include <string>
using namespace std;

struct Student {
    string name;
    int rollNo;

    Student(string n, int r) : name(n), rollNo(r) {}

    bool operator<(const Student &other) const {
        return rollNo < other.rollNo;
    }
};

int main() {
    multiset<Student> students;

    students.emplace("Ravi", 101);
    students.emplace("Aryan", 98);
    students.emplace("Viper", 105);
    students.emplace("Ayanokoji", 98);

    cout << "Students multiset sorted by roll number:" << endl;
    for (const auto &student : students)
        cout << "Name: " << student.name
             << ", Roll No: " << student.rollNo << endl;

    cout << "\nTotal students: " << students.size() << endl;

    return 0;
}

The output of the above code is given below −

Students multiset sorted by roll number:
Name: Aryan, Roll No: 98
Name: Ayanokoji, Roll No: 98
Name: Ravi, Roll No: 101
Name: Viper, Roll No: 105

Total students: 4

Exception Handling with emplace()

The following example explains multiset::emplace() function when there is an exception. Here, negative value is not allowed, so the Demo constructor will throw an exception, but there will not be any change in the multiset.

#include <iostream>
#include <set>
#include <stdexcept>
using namespace std;

struct Demo {
    int val;
    Demo(int v){
        if (v < 0)
            throw invalid_argument("\nNegative value not allowed");
        val = v;
    }
    bool operator<(const Demo &other) const { return val < other.val; }
};

int main() {
    multiset<Demo> objs = {10, 3, 24};
    cout << "Multiset values before exception: ";
    for (auto &d : objs)
        cout << d.val << " ";

    try {
        // It will throw an exception during construction
        objs.emplace(-5);
    }
    catch (const exception &e){
        cout << "\nException!" << e.what() << endl;
    }

    cout << "Multiset values after exception: ";
    for (auto &d : objs)
        cout << d.val << " ";

    return 0;
}

The output of the above code is given below −

Multiset values before exception: 3 10 24 
Exception!
Negative value not allowed
Multiset values after exception: 3 10 24

Type Mismatch Error with emplace()

In this example, we have an int type multiset. If value other than int is inserted using emplace, it will throw an error. Try uncommenting nums.emplace("30") tp see the compilation error.

#include <iostream>
#include <set>
using namespace std;

int main() {
    multiset<int> nums = {30, 10, 20, 40, 30};
    nums.emplace(10);
    nums.emplace(20);

    // It will give a compilation error
    // Uncomment it to see the error
    // nums.emplace("30");

    cout << "Elements: ";
    for (int n : nums)
        cout << n << " ";

    return 0;
}

The output of the code is given below −

Elements: 10 10 20 20 30 30 40
multiset.htm
Advertisements