Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since <code>u</code> is a vector of <code>std::pair&lt;double, std::string&gt;</code>, you will want to have the corresponding comparison function called. Since the name alone is not sufficient, you will have to dismabiguate it for the compiler by casting it to a pointer with the right function pointer type. In your case it is a function that takes two const references to the pair type and returns a bool - so the function pointer type you have to cast to is exactly that:</p> <pre><code>bool (*)(const std::pair&lt;int, int&gt; &amp;, const std::pair&lt;int, int&gt; &amp;) </code></pre> <p>Together that makes a pretty ugly cast:</p> <pre><code>std::sort(u.begin(), u.end(), static_cast&lt;bool (*)(const std::pair&lt;int, int&gt; &amp;, const std::pair&lt;int, int&gt; &amp;)&gt;(&amp;Misc::sortPair)); </code></pre> <p>Whoa.</p> <p>Better use some typedefs to clarify what you are doing:</p> <pre><code>//includes as they were... typedef std::pair&lt;double, std::string&gt; dsPair; //or something more meaningful class Misc { public: //Comment out the next three lines to compile without problems static bool sortPair(const std::pair&lt;int, int&gt; &amp;a, const std::pair&lt;int, int&gt; &amp;b){ return a.first &lt; b.first; } static bool sortPair(dsPair const&amp; a, dsPair const&amp; b){ return a.first &lt; b.first; } }; int main () { std::vector&lt;dsPair&gt; u{ {10.0, "ten"}, {5.0, "five"}, {1.0, "one"} }; /** the function pointer typedef * It takes a bit getting used to, but no worries, * you won't have to do it THAT often: **/ typedef bool(*dsPairCompFunc)(dsPair const&amp;, dsPair const&amp;); //and now the cast is much clearer: std::sort(begin(u), end(u), static_cast&lt;dsPairCompFunc&gt;(&amp;Misc::sortPair)); for (auto&amp; e : u){ std::cout &lt;&lt; e.first &lt;&lt; "\n"; } return 0; } </code></pre> <p>I changed some of the old C++03 stuff to C++11 in case your compiler supports it.</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