【问题标题】:set::key_comp vs set::value_comp in C++?C++ 中的 set::key_comp 与 set::value_comp?
【发布时间】:2017-01-13 09:33:15
【问题描述】:

set::key_compC++ 中的 set::value_comp 有什么区别?转到 cplusplus.com 页面没有显着差异。 此外,在 set::key_comp 和相关的 set::value_comp 页面上 最后一句是“(...) key_comp 和它的兄弟成员函数 value_comp 是等价的。”

示例几乎相同:

http://www.cplusplus.com/reference/set/set/key_comp/

http://www.cplusplus.com/reference/set/set/value_comp/

【问题讨论】:

标签: c++ performance stl std stdset


【解决方案1】:

key_comp 定义了 keys 在容器中的顺序。

value_comp 定义容器中的顺序。

std::set 中,本质上,值是键,两者确实完全等价。但这并非在所有容器中都是如此,例如std::map,或者一般来说,在您可能构建的遵循 C++ 标准库容器约定的容器中。

还请注意,http://en.cppreference.com/w/ 是 C++ 的高级参考。它几乎代表了标准。

【讨论】:

    【解决方案2】:

    它们是相同的,任何实现都必须使它们都可用,因为std::set 必须满足Associative Container 的要求。

    这允许您编写适用于任何关联容器(标准库中的std::setstd::mapstd::multisetstd::multimap)的通用代码。

    【讨论】:

      【解决方案3】:

      keyvalue 是容器内的不同实体时,差异就出现了。

      对于像set 这样的容器,这两个术语的含义相同。

      虽然对于mapmultimap 之类的容器,keyvalue 是作为单个条目维护的独立实体。

      下面是一个例子,展示了它们的不同之处:

      std::set<int> myset;
      int highest1, highest2, highest3;
      typedef map<int, int> MyMap;
      MyMap mymap;
      
      std::set<int>::key_compare   myCompKeyForSet = myset.key_comp();
      std::set<int>::value_compare myCompValForSet = myset.value_comp();
      
      MyMap::key_compare   myCompKeyForMap = mymap.key_comp();
      MyMap::value_compare myCompValForMap = mymap.value_comp();
      
      
      for (int i=0; i<=5; i++) {
        myset.insert(i);
        mymap.insert(make_pair(i, 2*i));
      }
      
      //////SET///////
      
      highest1=*myset.rbegin();
      std::set<int>::iterator it=myset.begin();
      while ( myCompKeyForSet(*it, highest1) ) it++;
      std::cout << "\nhighest1 is " << highest1;  // prints 5
      
      
      highest2 = *myset.rbegin();
      it=myset.begin();
      while ( myCompValForSet(*it, highest2) ) it++;
      std::cout << "\nhighest2 is " << highest2;   // prints 5
      
      //////MAP///////
      
      MyMap::iterator it2 = mymap.begin();
      highest3 = mymap.rbegin()->first;
      while ( myCompKeyForMap((it2->first), highest3) ) it2++;
      std::cout << "\nhighest3 is " << highest3;     // prints 5
      
      std::pair<int,int> highest4 = *mymap.rbegin();    //must be defined as map's `value_type`
      it2 = mymap.begin();
      while ( myCompValForMap(*(it2), highest4) ) it2++;  // takes `value_type` which is `pair<int, int>` in this case. 
      std::cout << "\nhighest4 is " << highest4.second;   // prints 10
      

      Live demo

      正如我提到的,传递给value_compare 函数对象的参数必须是value_type&amp; 类型,所以我与那些说这两个set::key_comp 和@987654333 的人有点分歧 @ 在关联容器之间很容易兼容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-07
        • 2022-11-20
        • 1970-01-01
        • 1970-01-01
        • 2010-11-30
        • 1970-01-01
        相关资源
        最近更新 更多