Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Instead of creating two separate vectors/lists, the usual way to handle this is to create a single vector/list of objects that include both names and ages:</p> <pre><code>struct person { std::string name; int age; }; </code></pre> <p>To get a sort based on age, pass a comparator that looks at the ages:</p> <pre><code>std::sort(people.begin(), people.end(), [](auto const &amp;a, auto const &amp;b) { return a.age &lt; b.age; }); </code></pre> <p>In older C++ (pre C++11, so no lambda expressions) you can define the comparison as a member overload of <code>operator&lt;</code> or else as a function-object (an object that overloads <code>operator()</code>) to do the comparison:</p> <pre><code>struct by_age { bool operator()(person const &amp;a, person const &amp;b) const noexcept { return a.age &lt; b.age; } }; </code></pre> <p>Then your sort would look something like:</p> <pre><code>std::vector&lt;person&gt; people; // code to put data into people goes here. std::sort(people.begin(), people.end(), by_age()); </code></pre> <p>As for choosing between defining <code>operator&lt;</code> for the class, or using a separate comparator object as I show above, it's mostly a question of whether there's a single ordering that's "obvious" for this class.</p> <p>In my opinion, it's not necessarily obvious that sorting people would always happen by age. If, however, in the context of your program it would be obvious that sorting people would be done by age unless you explicitly specified otherwise, then it would make sense to implement the comparison as <code>person::operator&lt;</code> instead of in a separate comparison class the way I've done it above.</p>
 

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