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

来源:互联网 发布:2016年网络第一红歌 编辑:程序博客网 时间:2024/04/29 23:56

下面的代码示例演示如何使用 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   #endiftypedef 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



原创粉丝点击