Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The struct you have is fine, except that you may want to add an overload of <code>operator&lt;</code> to do comparison. Here I'm doing the "compare by name, then date" comparison:</p> <pre><code>// Add this as a member function to `entry`. bool operator&lt;(entry const &amp;other) const { if (name1 &lt; other.name1) return true; if (name1 &gt; other.name1) return false; // otherwise name1 == other.name1 // so we now fall through to use the next comparator. if (date &lt; other.date) return true; return false; } </code></pre> <p>[Edit: What's required is called a "strict weak ordering". If you want to get into detail about what the means, and what alternatives are possible, Dave Abrahams wrote quite a detailed post on <a href="http://cpp-next.com/archive/2010/02/order-i-say/" rel="nofollow">C++ Next</a> about it.</p> <p>In the case above, we start by comparing the name1 fields of the two. If <code>a&lt;b</code>, then we immediately return true. Otherwise, we check for <code>a&gt;b</code>, and if so we return false. At that point, we've eliminated <code>a&lt;b</code> and <code>a&gt;b</code>, so we've determined that <code>a==b</code>, in which case we test the dates -- if <code>a&lt;b</code>, we return true. Otherwise, we return false -- either the dates are equal, or <code>b&gt;a</code>, either of which means the test for <code>a&lt;b</code> is false. If the sort needs to sort out (no pun intended) which of those is the case, it can call the function again with the arguments swapped. The names will still be equal, so it'll still come down to the dates -- if we get false, the dates are equal. If we get true on the swapped dates, then what started as the second date is actually greater. ]</p> <p>The <code>operator&lt;</code> you define in the structure defines the order that will be used by default. When/if you want you can specify another order for the sorting to use:</p> <pre><code>struct byid { bool operator&lt;(entry const &amp;a, entry const &amp;b) { return a.id_number &lt; b.id_number; } }; std::vector&lt;entry&gt; entries; // sort by name, then date std::sort(entries.begin(), entries.end()); // sort by ID std::sort(entries.begin(), entries.end(), byid()); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload