C++ multimap::value_comp() Function



The C++ std::multimap::value_comp() function is a comparator that is used to return a comparison object that compare the elements stored in the multimap. This function helps to determine the order of the elements by comparing pairs using the multimap sorting criterion, which is defined by its comparison function. The time complexity of this function is constant i.e. O(1).

Syntax

Following is the syntax for std::multimap::value_comp() function.

value_compare value_comp() const;

Parameters

It does not accept any parameter.

Return value

This function returns a comparison object for element values.

Example

Let's look at the following example, where we are going to demonstrate the usage of value_comp() function.

#include 
#include 
int main()
{
    std::multimap a = {{1, "AB"}, {2, "BC"}, {1, "CD"}};
    auto b = a.value_comp();
    auto x = a.begin();
    auto y = std::next(x);
    std::cout << "Comparing First Two Elements: "
              << (b(*x, *y) ? "True" : "False") << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Comparing First Two Elements: False

Example

Consider the following example, where we are going to use the value_comp() to sort the elements of multimap.

#include 
#include 
#include 
#include 
int main()
{
    std::multimap a = {
        {2, "Ciaz"},
        {3, "Sail"},
        {1, "Audi"},
        {3, "Verna"}
    };
    std::vector> elements(a.begin(), a.end());
    auto x = a.value_comp();
    std::sort(elements.begin(), elements.end(), x);
    for (const auto& elem : elements) {
        std::cout << "{" << elem.first << ", " << elem.second << "}" << std::endl;
    }
    return 0;
}

Output

Output of the above code is as follows −

{1, Audi}
{2, Ciaz}
{3, Sail}
{3, Verna}

Example

In the following example, we are going to use the value_comp() to find the minimum and maximum elements in multimap.

#include 
#include 
#include 
int main()
{
    std::multimap a = {
        {1, 1},
        {2, 22},
        {2, 333},
        {3, 4444}
    };
    auto b = a.value_comp();
    auto x = *std::min_element(a.begin(), a.end(), b);
    auto y = *std::max_element(a.begin(), a.end(), b);
    std::cout << "Min Element: {" << x.first << ", " << x.second << "}" << std::endl;
    std::cout << "Max Element: {" << y.first << ", " << y.second << "}" << std::endl;
    return 0;
}

Output

If we run the above code it will generate the following output −

Min Element: {1, 1}
Max Element: {3, 4444}
multimap.htm
Advertisements