Note that there are some explanatory texts on larger screens.

plurals
  1. POOverload custom std::sort comparison function
    primarykey
    data
    text
    <p>When using std::sort, how can I overload the custom comparison function that I am using?</p> <pre><code>#include &lt;string&gt; #include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; 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(const std::pair&lt;double, std::string&gt; &amp;a, const std::pair&lt;double, std::string&gt; &amp;b){ return a.first &lt; b.first; } }; int main () { std::vector&lt;std::pair&lt;double, std::string&gt; &gt; u; u.push_back(std::make_pair(10.0, "ten")); u.push_back(std::make_pair(5.0, "five")); u.push_back(std::make_pair(1.0, "one")); std::sort(u.begin(), u.end(), Misc::sortPair); for (unsigned int i=0; i&lt; u.size(); i++){ std::cout &lt;&lt; u.at(i).first &lt;&lt; std::endl; } return 0; } </code></pre> <p>I can't get this to compile as it complains about:</p> <pre><code>unresolved overloaded function type </code></pre> <p>I can see that using "sortPair" could be somewhat ambiguous but I assumed that the compiler would be able to resolve this based on the types associated with the vector "u". Is there some way that I could specify which function/method to use in order to disambiguate the problem? Currently, commenting out the first sortPair function allows the code to be compiled and produces the correct sorted output. Of course, this is because it is not longer ambiguous. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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