Eh, sorry ah, but I realised that I mixed up the order myself. I should have come up with the edge cases and tested first. A correct version that places empty strings at the end would be:
EDIT:Code:bool Books::operator<(const Book &obj) const { if (obj.Author.empty()) { return !Author.empty(); } else if (Author.empty()) { return false; } return Author < obj.Author; }
Or slightly more succinctly:
Code:bool Books::operator<(const Book &rhs) const { if (rhs.Author.empty()) { return !Author.empty(); } return !Author.empty() && Author < rhs.Author; }
Last edited by laserlight; 01-06-2009 at 01:19 PM.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
It appears that the test that puts zero items last needs to be a bit more complicated:
Edit: I see you've already noticed that...Code:#include <iostream> #include <algorithm> #include <iterator> #include <cstdlib> class X { int n; public: X(): n(rand()%4) {} bool operator<(X rhv) const { if (n == 0) { return false; } else if (rhv.n == 0) { return true; } else { return n < rhv.n; } } friend std::ostream& operator<<(std::ostream& os, X x) { return os << x.n; } }; int main() { const unsigned max = 80; X arr[max] = {}; std::sort(arr, arr + max); std::copy(arr, arr + max, std::ostream_iterator<X>(std::cout, "")); }
Last edited by anon; 01-06-2009 at 01:28 PM.
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
I was going to also suggest that the books be a vector instead of an array. That would make the sorting easier, and the moving of the empty data to the end easier.
Would it not?
Ah, but your logic is slightly simpler. I should have tried to simplify the logic before trying to write the expression more succinctly. Consequently, we can more easily reduce the expression to:Originally Posted by anon
Code:bool Book::operator<(const Book& rhs) const { return !Author.empty() && (rhs.Author.empty() || Author < rhs.Author); }It would not make the sorting simpler, but there are other advantages, like having a dynamic size and not needing to manually manage memory.Originally Posted by Phyxashun
Last edited by laserlight; 01-06-2009 at 01:49 PM. Reason: Books -> Book
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)