I like it! You know, I have been learning more through reading this board, and posting; than I have learned from any book that I have found over the years.
Thanks!
Printable View
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;
}
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, ""));
}
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:Quote:
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.Quote:
Originally Posted by Phyxashun