C++ multimap::key_comp() Function



The C++ std::multimap::key_comp() function provides a comparison object, typically a function, used to compare the keys in the multimap. This comparator is essential for maintaining the order of elements, as it determines the sorting criteria for keys. It is used for sorting and ensuring consistent key comparisons throughout the multimap operations. The time complexity of this function is constant i.e.O(1).

Syntax

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

key_compare key_comp() const;

Parameters

It does not accept any parameter.

Return value

This function returns the comparison object.

Example

Let's look at the following example, where we are going to compare the keys in loop.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {{1, "One"}, {2, "Two"}, {3, "Three"}};
    auto x = a.key_comp();
    for (auto y = a.begin(); y != a.end(); ++y) {
        if (x(y->first, 3)) {
            std::cout << "Less than" << std::endl;
        } else {
            std::cout << "Not Less than" << std::endl;
        }
    }
    return 0;
}

Output

Output of the above code is as follows −

Less than
Less than
Not Less than

Example

Consider the following example, that iterates through the multimap and uses the key_comp() function to check if each key is less than the next key, ensuring the multimap is sorted correctly.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    a.insert({1, "AB"});
    a.insert({3, "BC"});
    a.insert({2, "CD"});
    auto x = a.key_comp();
    for (auto y = a.begin(); y != a.end(); ++y) {
        auto next = std::next(y);
        if (next != a.end()) {
            if (x(y->first, next->first)) {
                std::cout << y->first << " is less than " << next->first << std::endl;
            } else {
                std::cout << y->first << " is not less than " << next->first << std::endl;
            }
        }
    }
    return 0;
}

Output

Following is the output of the above code −

1 is less than 2
2 is less than 3

Example

In the following example, we are going to find and print elements with keys within a specified range using key_comp().

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a;
    a.insert({1, "A"});
    a.insert({2, "B"});
    a.insert({3, "C"});
    a.insert({4, "D"});
    auto comp = a.key_comp();
    int x = 2;
    int y = 4;
    for (auto z = a.begin(); z != a.end(); ++z) {
        if (!comp(z->first, x) && comp(z->first, y)) {
            std::cout << z->second << " is between " << x << " and " << y << "\n";
        }
    }
    return 0;
}

Output

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

B is between 2 and 4
C is between 2 and 4
multimap.htm
Advertisements