C++ STL 中的 map::value_comp() 函数


在本文中,我们将讨论 C++ STL 中 map::value_comp() 函数的工作原理、语法和示例。

C++ STL 中什么是 Map?

Map 是关联容器,便于存储由键值和映射值在特定顺序下组合而成的元素。在 map 容器中,数据始终在内部使用关联键进行排序。Map 容器中的值由其唯一键访问。

什么是 map::value_comp()?

map::value_comp() 是 C++ STL 中的内置函数,其在 header file. value_comp() returns a copy of the comparison object, which is used by the map container for the comparisons. By default, this object is less than the operator’s object, which works similar to less than operator.

它是一种函数指针或函数对象,可比较特定集合中两个同类型值的比较,如果第一个元素小于容器中的第二个元素,则返回 true,否则返回 false。

语法

Map_name.value_comp(key& k);

参数

此函数不接受任何参数。

返回值

此函数返回关联集合容器的比较对象。

示例

输入

map<char, int> newmap;
newmap[‘a’] = 1;
newmap[‘b’] = 2;
newmap[‘c’] = 3;
set<int>::value_compare cmp = myset.value_comp()

输出

1
2
3

示例

 在线演示

#include <iostream>
#include <map>
using namespace std;
int main() {
   map<char, int> TP = {
      { 'a', 10 },
      { 'b', 20 },
      { 'c', 30 },
      { 'd', 40 },
      { 'e', 50 },
   };
   auto temp = *TP.rbegin();
   auto i = TP.begin();
   cout <<"Elements in map are : \n";
   do {
      cout<< i->first << " = " << i->second<< endl;
   } while (TP.value_comp()(*i++, temp));
   return 0;
}

输出

Elements in map are :
a = 10
b = 20
c = 30
d = 40
e = 50

更新于:2020 年 4 月 15 日

1K+ 浏览量

启动您的 职业生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.