pls help to explain stl multiset's behavior for user-defined object
Thanks for your patience to read the entire post to understand my
confusion :) I have the user-defined class "tools": Code:
class tools{ Code:
tools toolArr[] = {tools("MS", "VC"), Code:
lhs=SUN.Java rhs=MS.VC possible that object tools("MS","SQL") is considered equal to tools("MS","VC")? Please take a look at "line 1", I intentionally did not compare their names to make them different. But it did not matter. I thought count() should return 0, but apparently it returns 2. Second, why is the operator< called so many times? For instance, lhs=SUN.Java rhs=MS.VC lhs=SUN.Java rhs=MS.VC is printed twice in a row which indicates operator< was called twice. What's actually happening behind STL's multiset? Is search tree the underlying data structure of multiset? Struggled on this for quite a while. Really appreciate your explanation of what's going on here. |
The multiset sorts the elements that you put into it. See http://www.sgi.com/tech/stl/multiset.html, in particular note that the default for Compare is less<Key>, and that it should have a Strict Weak Ordering. I think your operator< does not since (tool1 < tool2) would compare a different set of strings than (tool2 < tool1).
|
Quote:
In addition, what about operator==? what does count() actually do? It should take Key which an object of tools and then look it up in the underlying RB-tree, right? I just cannot understand why tools("MS", "SQL") and tools("MS", "VC") are considered equal to each other. My plain thinking is equality should be involved in count(). Maybe I am dead wrong. |
Got it. It was due to strict weak ordering used by multiset
which is defined by operator<. The current operator< used by class tools is saying as long as two objects have the same "company" string, they are equal. So by changing operator<, I could see the difference. |
edit: Oh, I see you've figured it out already.
Quote:
Code:
tools tool1("aa", "bb"), tool2("ab", "ab"); Quote:
|
Quote:
is: return string("ab") < string("aa"). I don't know why it should do "ab" < "bb", assuming you meant they are actually strings, not char[]. In the function operator<, the second field, i.e., name, is not used at all. I changed function operator< to this and it seems work the way I preferred: Code:
return lhs.company < rhs.company || (lhs.company == rhs.company && lhs.name < rhs.name) ; |
Quote:
|
All times are GMT -5. The time now is 10:45 AM. |