Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For pointers in general you could do this:</p> <pre><code> #include &lt;ctime&gt; #include &lt;vector&gt; #include &lt;cstdlib&gt; #include &lt;algorithm&gt; #include &lt;functional&gt; #include &lt;type_traits&gt; namespace util { struct sort_pointers { bool operator() ( int *a, int *b ) { return *a &lt; *b; } }; template &lt;typename T, bool is_pointer = !std::tr1::is_pointer&lt;T&gt;::value&gt; struct sort_helper { typedef std::less&lt;T&gt; wont_compare_pointers; }; template &lt;typename T&gt; struct sort_helper&lt;T,false&gt; { }; template &lt;typename Iterator&gt; void sort( Iterator start, Iterator end ) { std::sort( start, end, sort_helper &lt; typename Iterator::value_type &gt;::wont_compare_pointers() ); } template &lt;typename Iterator, class Func&gt; void sort( Iterator start, Iterator end, Func f ) { std::sort( start, end, f ); } } int main() { std::vector&lt;int&gt; v1; std::vector&lt;int*&gt; v2; srand(time(0)); for( int i = 0; i &lt; 10; ++i ) { v1.push_back(rand()); } util::sort( v1.begin(), v1.end() ); for( int i = 0; i &lt; 10; ++i ) { v2.push_back(&amp;v1[i]); } /* util::sort( v2.begin(), v2.end() ); */ //fails. util::sort( v2.begin(), v2.end(), util::sort_pointers() ); return 0; } </code></pre> <p><code>std::tr1::is_pointer</code> was just what it was called in Visual Studio 2008, but I think Boost has one too, and newer compiles might provide it as <code>std::is_pointer</code>. I'm sure someone would be able to write a prettier solution, but this appears to work.</p> <p>But I must say, I agree with cogwheel, there is no reason for this, the programmer should be able to see if this is going to be a problem and act accordingly.</p> <p>Addition:</p> <p>You can generalize it a bit more I think, to automatically select a functor that will dereference the pointers and compare the values:</p> <pre><code>namespace util { template &lt;typename T&gt; struct sort_pointers { bool operator() ( T a, T b ) { return *a &lt; *b; } }; template &lt;typename T, bool is_pointer = !std::tr1::is_pointer&lt;T&gt;::value&gt; struct sort_helper { typedef std::less&lt;T&gt; compare; }; template &lt;typename T&gt; struct sort_helper&lt;T,false&gt; { typedef sort_pointers&lt;T&gt; compare; }; template &lt;typename Iterator&gt; void sort( Iterator start, Iterator end ) { std::sort( start, end, sort_helper &lt; typename Iterator::value_type &gt;::compare() ); } } </code></pre> <p>That way you don't have to think about if you're providing it with pointers to compare or not, it will automatically be sorted out.</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