Thanks for your patience to read the entire post to understand my
confusion I have the user-defined class "tools":
in main(),I want to use multiset on user-defined objects:
What bothers me is that the above program generates the following output:
First of all, how come the operator== is not called at all? How could it be
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.
confusion I have the user-defined class "tools":
Code:
class tools{
public:
tools( ......) {}
friend bool operator< (const tools& lhs, const tools& rhs) {
cout<<"lhs="<<lhs.company<<"."<<lhs.name
<<" rhs="<<rhs.company<<"."<<rhs.name<<endl;
return lhs.company < rhs.company;
}
friend bool operator== (const tools& lhs, const tools& rhs) {
cout<<" in op=="<<endl;
return lhs.company == rhs.company ;
//note, without &&lhs.name==rhs.name; // line 1
}
private:
string company;
string name;
};
Code:
tools toolArr[] = {tools("MS", "VC"),
tools("SUN", "Java"),
tools("MS", "Word") ,
tools("Apple", "Mac")
};
int Size = sizeof(toolArr)/sizeof(tools);
multiset<tools> toolSet(toolArr, toolArr+Size);
string cmpy("MS");
cout << "There are " <<toolSet.count(tools(cmpy, "SQL"))
<< " " << cmpy << " tools in the set" << endl << endl;
}
Code:
lhs=SUN.Java rhs=MS.VC lhs=SUN.Java rhs=MS.VC lhs=MS.Word rhs=SUN.Java lhs=MS.Word rhs=MS.VC lhs=MS.Word rhs=SUN.Java lhs=MS.Word rhs=SUN.Java lhs=Apple.Mac rhs=SUN.Java lhs=Apple.Mac rhs=MS.Word lhs=Apple.Mac rhs=MS.VC lhs=Apple.Mac rhs=MS.VC lhs=MS.SQL rhs=MS.Word lhs=MS.SQL rhs=SUN.Java lhs=MS.Word rhs=MS.SQL lhs=MS.VC rhs=MS.SQL lhs=Apple.Mac rhs=MS.SQL There are 2 MS tools in the set
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.
Comment