vector sort just reversing input with custom comparator
<p>I get some strange behavior when sorting a c++ vector with at custom comparator class.</p>

<p>I want to sort a array of indexes based on some values in an other array. But as far as I can see the sort function just reverses my indexes. I've done some logging of the compare function, at it seems to be working just fine.</p>

<p>Is there anyone who can spot what I'm doing wrong?</p>

<p>My code:</p>

<pre><code>template&lt;class T&gt;
class Comparator {
   vector&lt;T&gt; &amp; data;
public:
  bool operator()(int a, int b) {
    return data.at(a) &lt; data.at(b) ? -1 : (data.at(a) &gt; data.at(b) ? 1 : 0);
  }

  Comparator(vector&lt;T&gt; &amp; data) : data(data) {}
};

void sortTest2() {
  //SETUP
  int n = 5;
  vector&lt;int&gt; indexes(n);
  newIdAr(indexes, n); //init to {0,1,2,3,4}
  vector&lt;double&gt; data(n);
  randomData(data, n); //Init to radom data
  Comparator&lt;double&gt; comparator(data);

  //TEST
  print(indexes, data, n); // Prints [0.00125126, 0.563585, 0.193304, 0.808741]
  sort(indexes.begin(), indexes.end(),comparator);
  print(indexes, data, n); // Prints [0.808741, 0.193304, 0.563585, 0.00125126]
  sort(indexes.begin(), indexes.end(),comparator);
  print(indexes, data, n); // Prints [0.00125126, 0.563585, 0.193304, 0.808741]
  cout &lt;&lt; "Shuffle" &lt;&lt; endl;
  random_shuffle(indexes.begin(), indexes.end());
  print(indexes, data, n);
  sort(indexes.begin(), indexes.end(), comparator);
  print(indexes, data, n);
}
</code></pre>

<p>My output:</p>

<pre><code>[0.00125126, 0.563585, 0.193304, 0.808741, 0.585009]
[0.585009, 0.808741, 0.193304, 0.563585, 0.00125126]
[0.00125126, 0.563585, 0.193304, 0.808741, 0.585009]
Shuffle
[0.193304, 0.00125126, 0.585009, 0.563585, 0.808741]
[0.808741, 0.563585, 0.585009, 0.00125126, 0.193304]
</code></pre>

<p><em>Code for the auxiliary functions:</em></p>

<pre><code>#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;algorithm&gt;
using namespace std;

void print(vector&lt;int&gt; &amp; sort, vector&lt;double&gt; &amp; data, int N) {
  cout &lt;&lt; "[";
  for (int i = 0; i &lt; N - 1; ++i) {
    cout &lt;&lt; data[sort[i]] &lt;&lt; ", ";
  }
  cout &lt;&lt; data[sort[N - 1]] &lt;&lt; "]" &lt;&lt; endl;
}

void newIdAr(vector&lt;int&gt; &amp; ar, int N) {
  for (int i = 0; i &lt; N; ++i) {
    ar[i] = i;
  }
}

void randomData(vector&lt;double&gt; &amp; data, int n) {
  for (int i = 0; i &lt; n; ++i) {
    data[i] = ((double) rand()) / RAND_MAX;
  }
}
</code></pre>
