C++ multimap::value_comp() 函数



C++ 的std::multimap::value_comp() 函数是一个比较器,用于返回一个比较对象,该对象比较存储在 multimap 中的元素。此函数通过使用 multimap 排序标准(由其比较函数定义)比较对来帮助确定元素的顺序。此函数的时间复杂度是常数,即 O(1)。

语法

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

value_compare value_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.

返回值

此函数返回一个用于元素值的比较对象。

示例

让我们看下面的例子,我们将演示 value_comp() 函数的使用。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> 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; }

输出

以上代码的输出如下:

Comparing First Two Elements: False

示例

考虑以下示例,我们将使用 value_comp() 对 multimap 的元素进行排序。

Open Compiler
#include <iostream> #include <map> #include <vector> #include <algorithm> int main() { std::multimap<int, std::string> a = { {2, "Ciaz"}, {3, "Sail"}, {1, "Audi"}, {3, "Verna"} }; std::vector<std::pair<int, std::string>> 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; }

输出

以上代码的输出如下:

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

示例

在下面的示例中,我们将使用 value_comp() 查找 multimap 中的最小和最大元素。

Open Compiler
#include <iostream> #include <map> #include <algorithm> int main() { std::multimap<int, int> 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; }

输出

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

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