STL's key_comp()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • p vs np
    New Member
    • Mar 2009
    • 26

    STL's key_comp()

    I was going through the stl::key_comp() function and found it's implementation to be pretty straight forward when it came implementation on integers.

    For eg:
    Code:
    #include <iostream>
    #include <set>
    using namespace std;
    
    int main ()
    {
      set<int> myset;
      set<int>::key_compare mycomp;
      set<int>::iterator it;
      int i,highest;
    
      mycomp = myset.key_comp();
    
      for (i=0; i<=5; i++) myset.insert(i);
    
      cout << "myset contains:";
    
      highest=*myset.rbegin();
      it=myset.begin();
      do {
        cout << " " << *it;
      } while ( mycomp(*it++,highest) );
    
      cout << endl;
    
      return 0;
    }
    would give out the result [0,1,2,3,4,5] on comparing each of the integers in the set.

    I wanted to try the same on a higher-level data straucture such as a structure of type:
    Code:
    struct node
    {
           int a,b;
    };
    but had some problems. It gives me an error whenever i want to insert a set element, as the default comparison function does not allow it.

    So, how do I use key_comp() and value_comp() to define our own comparison function??
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You probably need to define some of the comparison functions (operator== for example) on or for your struct.

    Or define a binary predicate comparison class that can be passed to set as a template parameter when you want to create a set of those structures.

    The basic point is that set contins unique entries so it needs to be able to compare the objects it stores, it can easily do that for the basic types but for user defined types you need to provide the set with a way of comparing different instances of the type.

    Read this

    Comment

    • newb16
      Contributor
      • Jul 2008
      • 687

      #3
      Set requires operator< to be defined on keys, and to function properly (i.e. object considered by the container equal to itself and not equal to an object that differs from it), condition !(a < b) && !(b<a) must be true only if a==b. std::pair for example, compares the first items of both arguments and only if they are equal, compares the second items.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Originally posted by newb16
        Set requires operator< to be defined on keys,
        Or, you write a binary predicate function that takes two arguments of the set type and returns a bool. When you create the set object there is a constructor that takes a pointer to this function for later use when you need to compare objects in the set.

        Comment

        Working...