C++ multimap::key_comp() 函数



C++ 的std::multimap::key_comp()函数提供一个比较对象,通常是一个函数,用于比较multimap中的键。这个比较器对于维护元素的顺序至关重要,因为它决定了键的排序标准。它用于排序并确保在整个multimap操作中键比较的一致性。此函数的时间复杂度为常数,即 O(1)。

语法

以下是std::multimap::key_comp()函数的语法。

key_compare key_comp() const;

参数

它不接受任何参数。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

此函数返回比较对象。

示例

让我们看下面的例子,我们将循环比较键。

Open Compiler
#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; }

输出

以上代码的输出如下:

Less than
Less than
Not Less than

示例

考虑下面的例子,它遍历multimap并使用key_comp()函数检查每个键是否小于下一个键,确保multimap正确排序。

Open Compiler
#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; }

输出

以上代码的输出如下:

1 is less than 2
2 is less than 3

示例

在下面的例子中,我们将使用key_comp()查找并打印具有指定范围内的键的元素。

Open Compiler
#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; }

输出

如果我们运行上面的代码,它将生成以下输出:

B is between 2 and 4
C is between 2 and 4
multimap.htm
广告