STL Multiset with Class Objects sorted based on its member variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Digital Don
    New Member
    • Jan 2007
    • 19

    STL Multiset with Class Objects sorted based on its member variable

    Hi,

    I was looking at the MultiSet STL structure with some "less" keyword. I was told that we can use the "MultiSet" STL structure to automatically sort the content.

    Is it possible to store and Sort CLASS objects based on a class variable value in it .

    i.e.

    multiset <Event, less<Event> > _queue;

    where Event is a class with the variables in it

    "processID
    Time
    typeofEvent"

    How do I specify that the class objects in the multiset be sorted based on the TIME value of the class object?

    Thank You in Advance.
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    You can overload operator< for your class. That is, you write a function with the signature [CODE=cpp]bool operator<(const Event& other)[/CODE] that returns based on whether the caller object's time value (use the 'this' pointer if you want) is less than the passed in object's time value.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      You can also create your multiset using a 3rd template parameter for the address of the function you want to use to order your objects.

      This avoids implementing a class operator< when you don't really need it.

      Comment

      • Digital Don
        New Member
        • Jan 2007
        • 19

        #4
        Can u explain or provide a link to the 3rd template of Multiset?

        Thank You.


        Originally posted by weaknessforcats
        You can also create your multiset using a 3rd template parameter for the address of the function you want to use to order your objects.

        This avoids implementing a class operator< when you don't really need it.

        Comment

        • Laharl
          Recognized Expert Contributor
          • Sep 2007
          • 849

          #5
          The STL declaration of multiset is [CODE=cpp]multiset<class Key, class Comparator = less<Key>, class Allocator = Allocator<Key> >[/CODE] Thus, it's the second parameter you're interested in here, not the third. This works because the name of a function acts as a pointer to that function.

          [CODE=cpp]
          class foo{
          private
          int bar;
          //...
          }

          bool myfunc(const foo& one, const foo& two){
          return one.bar<two.bar ;
          }

          multiset<foo, myfunc> myset;
          [/CODE]

          Comment

          Working...