Hi Everybody. If any of you know how to make an STL set of classes or structs, that would be cool. Which operators do you need to implements so if I have myclass, I can have an stl set of type myclass. Examples are welcome too.
Hi Everybody. If any of you know how to make an STL set of classes or structs, that would be cool. Which operators do you need to implements so if I have myclass, I can have an stl set of type myclass. Examples are welcome too.
You need a way to compare instances of your class. One way is an operator<, which makes sense if there is one obvious way to compare two class objects. Another option is to write a comparison class whose operator() compares two class instances like a global operator< would. If you use that then you have to specify it when you declare your set. If you just use operator< then the set will automatically use that for its sorting.
First method as described by Daved...
Or, second method as described above...Code:#include <set> ... struct foo { int bar; }; bool operator<(const foo& left, const foo& right) { return left.bar < right.bar; } int main() { std::set<foo> fooset; // Uses operator< automatically for sorting items in the container ... return 0; }
If the data member you are comparing happens to be private then you'll need to make adjustments, either declaring operator< as a friend to the class/struct if you use that method, or creating accessor functions for returning the value of those private data members so they can be compared.Code:#include <set> ... struct foo { int bar; }; struct comp { inline bool operator()(const foo& left,const foo& right) { return left.bar < right.bar; } }; int main() { std::set<foo,comp> fooset; // Uses comparison struct/class object comp to sort the container ... return 0; }
[edit]Yay, my 2000th post, I thought for sure I was still around 1997 or so...[/edit]
Last edited by hk_mp5kpdw; 07-16-2007 at 06:10 AM.
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
To be pedantic: a predicate like comp should not change its state after a call or a copy. After all, if a and b do not change, then (a < b) should likewise not change. As such, it would be better to write:
Code:struct comp { inline bool operator()(const foo& left,const foo& right) const { return left.bar < right.bar; } };
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)