Set :: key_comp vs set :: value_comp in C ++?

What is the difference between set :: key_comp vs set :: value_comp in C ++ ? Going to cplusplus.com does not make a significant difference. In addition, on set :: key_comp and related pages set :: value_comp, the last sentence is "(...) key_comp, and its member-function member-value_value value_comp is equivalent to".

The examples are almost the same:

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

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

+4
source share
3 answers

key_comp defines the order of keys in the container.

value_comp .

std::set, , , , . , . std::map , , , , ++.

, http://en.cppreference.com/w/ ++. .

+3

, , std::set .

, (std::set, std::map, std::multiset, std::multimap ).

+3

, key value - .

, set, .

, map multimap, key value , .

, , :

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 `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

, value_compare value_type&, , set::key_comp set::value_comp ,

+1

Source: https://habr.com/ru/post/1666701/


All Articles