Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well, the short answer would be to not use <a href="http://en.cppreference.com/w/cpp/algorithm/qsort" rel="nofollow"><code>std::qsort</code></a> at all, but <a href="http://en.cppreference.com/w/cpp/algorithm/sort" rel="nofollow"><code>std::sort</code></a>. But unfortunately the latter won't work, since <code>unsigned int[3]</code> is not assignable. So here's the easiest <code>std::qsort</code> solution.</p> <p>First we define a custom comparator function:</p> <pre><code>// return -1 if a before b, 1 if after, 0 if equal int compare(const void *a, const void *b) { const unsigned int *arg1 = reinterpret_cast&lt;const unsigned int*&gt;(a); const unsigned int *arg2 = reinterpret_cast&lt;const unsigned int*&gt;(b); if(arg1[2] &gt; arg2[2]) return -1; if(arg1[2] &lt; arg2[2]) return 1; return 0; } </code></pre> <p>Which we then use to sort the array. Keep in mind that <code>work</code> is an array of arrays, and thus <code>work[0]</code> is an array of 3 <code>unsigned int</code>s, there's no pointer indirection involved in any way. So it's perfectly suited for being sorted by <code>std::qsort</code>:</p> <pre><code>std::qsort(work, sizeof(work)/sizeof(work[0]), sizeof(work[0]), compare); </code></pre> <p>By the way, the third element is indexed with <code>2</code>, since we usually start to count at <code>0</code> in C++ (and many other programming languages).</p> <p><strong>EDIT:</strong> Though, the best solution would indeed be to drop this array of arrays and use something more suited to C++, like a <code>std::vector</code> of <code>std::array&lt;unsigned int,3&gt;</code>s (or any other datastructure that fits a bit more to the actual context):</p> <pre><code>typedef std::array&lt;unsigned int,3&gt; uint3; std::vector&lt;uint3&gt; work(N); </code></pre> <p>Which can then be sorted with a simple:</p> <pre><code>std::sort(std::begin(work), std::end(work), [](const uint3 &amp;a, const uint3 &amp;b) { return a[2] &gt; b[2]; }); </code></pre> <p>Or, if you don't have C++11 (though in this case you won't have <code>std::array</code> either and need to start thinking about a resonable datastructure apart from a mere 3-array):</p> <pre><code>struct compare { bool operator()(const uint3 &amp;a, const uint3 &amp;b) const { return a[2] &gt; b[2]; } }; std::sort(work.begin(), work.end(), compare()); </code></pre> <p>As a bonus to much clearer code, you also most probably get a slight performance boost of <code>std::sort</code> over <code>std::qsort</code>.</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