You have a good structure, except that you can add operator<
overloading for comparison. Here I compare the comparison "by name, then date":
// Add this as a member function to `entry`. bool operator<(entry const &other) const { if (name1 < other.name1) return true; if (name1 > other.name1) return false; // otherwise name1 == other.name1 // so we now fall through to use the next comparator. if (date < other.date) return true; return false; }
[Edit: what is required is called "strict weak ordering." If you want to talk in detail about what tools and which alternatives are possible, Dave Abrahams wrote a rather detailed post in C ++ Next about this.
In the above example, we will start by comparing the name1 fields of the two. If a<b
, then we immediately return true. Otherwise, we check a>b
, and if so, we return false. At this point, we excluded a<b
and a>b
, so we determined that a==b
, in which case we check the dates - if a<b
, we return true. Otherwise, we return false - either the dates are equal, or b>a
, or of which means that the test for a<b
is false. If sorting should be sorted (no pun intended), which one is the case, he can again call the function with the replacement of arguments. Names will still be equal, so they will go up to dates - if we get false, the dates will be equal. If we return on dates with a replacement, then what started on the second date is actually more. ]
operator<
that you define in the structure determines the order that will be used by default. When / if you want, you can specify a different sort order to use:
struct byid { bool operator<(entry const &a, entry const &b) { return a.id_number < b.id_number; } }; std::vector<entry> entries;
source share