如何使用set::key_comp 和 set::value_comp 标准模板库 (STL) 函数

这篇博客介绍了如何在Visual C++中利用STL的set容器,特别是set::key_comp和set::value_comp函数,进行数据比较操作。通过示例代码,展示了这两个函数在标准模板库中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面的代码示例演示如何使用 Visual C++ set::key_comp 和 set::value_comp 的 STL 功能

所需要的头文件:<set>


原型

   template<class _K, class _Pr, class _A>
   class set {
   public:
   // Function 1:

      key_compare key_comp() const;

   // Function 2:
      value_compare value_comp() const;
   }
注意在原型中的类/参数名称可能与中的头文件的版本不匹配。一些已被修改以提高可读性。


说明

Key_comp 函数返回存储的函数对象,用于确定受控序列中元素的顺序。Value_comp 函数将返回相同的功能的函数对象。
示例代码:
// 
// 
// Compile options needed: -GX
// 
// SetComp.cpp:
//      Illustrates how to use the key_comp function to obtain a
//      function pointer that is the stored function object that
//      determines the order of elements in the controlled sequence.
//      It also illustrates how to use the value_comp function to
//      obtain a function pointer that is the stored function object
//      that determines the order of the elements in the controlled
//      sequence (same as key_comp result).
// 
// Functions:
// 
//    key_comp     Returns a function pointer to the function that
//                 determines the order of elements in the controlled
//                 sequence.
//    value_comp   Returns a function pointer to the function that
//                 determines the order of elements in the controlled
//                 sequence (same as key_comp).
// 
// Written by Derek Jamison
// of Microsoft Technical Support,
// Copyright (c) 1996 Microsoft Corporation. All rights reserved.
// 

#pragma warning(disable:4786)

#include <set>
#include <iostream>

#if _MSC_VER > 1020   // if VC++ version is > 4.2
   using namespace std;  // std c++ libs implemented in std
   #endif

typedef set<int,less<int>,allocator<int> > SET_INT;

void truefalse(int x)

{
  cout << (x?"True":"False") << endl;
}

void main() {

  SET_INT s1;

  cout << "s1.key_comp()(8,10) returned ";
  truefalse(s1.key_comp()(8,10));  // True

  cout << "s1.value_comp()(8,10) returned ";
  truefalse(s1.value_comp()(8,10));  // True

  cout << "s1.key_comp()(10,8) returned ";
  truefalse(s1.key_comp()(10,8));  // False

  cout << "s1.value_comp()(10,8) returned ";
  truefalse(s1.value_comp()(10,8));  // False

  cout << "s1.key_comp()(8,8) returned ";
  truefalse(s1.key_comp()(8,8));  // False

  cout << "s1.value_comp()(8,8) returned ";
  truefalse(s1.value_comp()(8,8));   // False
}

程序输出:
s1.key_comp()(8,10) returned True
s1.value_comp()(8,10) returned True
s1.key_comp()(10,8) returned False
s1.value_comp()(10,8) returned False
s1.key_comp()(8,8) returned False
s1.value_comp()(8,8) returned False



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值