Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy std::sort doesn't accept Compare classes declared within a function
    primarykey
    data
    text
    <p>I was at work, writing the Comparators in a function (to move later, when I decided where was best), and noticed this peculiarity. I thought about it for a while, and realized I do not understand exactly why the code will not compile if I use the inner comparators, but the outer one is fine. </p> <p>Any explanations?</p> <p>Quick Test harness: </p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; class CompareMe { public: CompareMe(int in) : toCompare(in){} int toCompare; }; class Comparators { public: bool operator()(CompareMe * first, CompareMe * second) { return first-&gt;toCompare &lt; second-&gt;toCompare; } }; class ComparatorsOuter : public Comparators{}; int main() { class ComparatorsInner : public Comparators{}; std::vector&lt;CompareMe *&gt; compares; compares.push_back(new CompareMe(0)); compares.push_back(new CompareMe(1234)); compares.push_back(new CompareMe(163)); compares.push_back(new CompareMe(6)); compares.push_back(new CompareMe(12)); //This works, and properly sorts the array ComparatorsOuter comparator; std::sort(compares.begin(), compares.end(), comparator); //Uncomment out the sort below and it will not compile. ComparatorsInner comparatorInner; //std::sort(compares.begin(), compares.end(), comparatorInner); std::vector&lt;CompareMe *&gt;::iterator it; for(it = compares.begin(); it != compares.end(); ++it) { std::cout &lt;&lt; (*it)-&gt;toCompare &lt;&lt; std::endl; } } </code></pre> <blockquote> <p>error: no matching function for call to '<code>sort(__gnu_cxx::__normal_iterator&lt;CompareMe**, std::vector&lt;CompareMe*, std::allocator&lt;CompareMe*&gt; &gt; &gt;, __gnu_cxx::__normal_iterator&lt;CompareMe**, std::vector&lt;CompareMe*, std::allocator&lt;CompareMe*&gt; &gt; &gt;, main()::ComparitorInner&amp;)</code>' </p> </blockquote>
    singulars
    1. This table or related slice is empty.
    plurals
    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