矢量排序只是使用自定义比较器反转输入

vector sort just reversing input with custom comparator

本文关键字:比较器 自定义 输入 排序      更新时间:2023-10-16

在用at自定义比较器类对c++向量进行排序时,我得到了一些奇怪的行为。

我想根据另一个数组中的一些值对索引数组进行排序。但就我所见,排序函数只是反转了我的索引。我已经对compare函数进行了一些日志记录,它似乎运行得很好。

有人能发现我做错了什么吗?

我的代码:

template<class T>
class Comparator {
   vector<T> & data;
public:
  bool operator()(int a, int b) {
    return data.at(a) < data.at(b) ? -1 : (data.at(a) > data.at(b) ? 1 : 0);
  }
  Comparator(vector<T> & data) : data(data) {}
};
void sortTest2() {
  //SETUP
  int n = 5;
  vector<int> indexes(n);
  newIdAr(indexes, n); //init to {0,1,2,3,4}
  vector<double> data(n);
  randomData(data, n); //Init to radom data
  Comparator<double> 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 << "Shuffle" << endl;
  random_shuffle(indexes.begin(), indexes.end());
  print(indexes, data, n);
  sort(indexes.begin(), indexes.end(), comparator);
  print(indexes, data, n);
}

我的输出:

[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]

辅助功能代码:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print(vector<int> & sort, vector<double> & data, int N) {
  cout << "[";
  for (int i = 0; i < N - 1; ++i) {
    cout << data[sort[i]] << ", ";
  }
  cout << data[sort[N - 1]] << "]" << endl;
}
void newIdAr(vector<int> & ar, int N) {
  for (int i = 0; i < N; ++i) {
    ar[i] = i;
  }
}
void randomData(vector<double> & data, int n) {
  for (int i = 0; i < n; ++i) {
    data[i] = ((double) rand()) / RAND_MAX;
  }
}
如果第一个参数低于第二个参数,则比较器应返回true,否则返回false。返回0、-1和1在代码中无效。

您可以通过分析比较器的operator()签名来实现这一点:

bool operator()(int a, int b)

我认为你的实现应该是:

bool operator()(int a, int b) {
    return data.at(a) < data.at(b);
}