By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,172 Members | 1,092 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,172 IT Pros & Developers. It's quick & easy.

STL Multiset with Class Objects sorted based on its member variable

Digital Don
P: 19
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.
Mar 5 '08 #1
Share this Question
Share on Google+
4 Replies


Expert 100+
P: 849
You can overload operator< for your class. That is, you write a function with the signature
Expand|Select|Wrap|Line Numbers
  1. bool operator<(const Event& other)
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.
Mar 5 '08 #2

weaknessforcats
Expert Mod 5K+
P: 9,197
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.
Mar 5 '08 #3

Digital Don
P: 19
Can u explain or provide a link to the 3rd template of Multiset?

Thank You.


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.
Mar 7 '08 #4

Expert 100+
P: 849
The STL declaration of multiset is
Expand|Select|Wrap|Line Numbers
  1. multiset<class Key, class Comparator = less<Key>, class Allocator = Allocator<Key> >
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.

Expand|Select|Wrap|Line Numbers
  1. class foo{
  2.  private
  3.   int bar;
  4.  //...
  5. }
  6.  
  7. bool myfunc(const foo& one, const foo& two){
  8.  return one.bar<two.bar;
  9. }
  10.  
  11. multiset<foo, myfunc> myset;
  12.  
Mar 7 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.