矢量排序只是使用自定义比较器反转输入
vector sort just reversing input with custom comparator
在用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;
}
}
您可以通过分析比较器的operator()
签名来实现这一点:
bool operator()(int a, int b)
我认为你的实现应该是:
bool operator()(int a, int b) {
return data.at(a) < data.at(b);
}
相关文章:
- std::设置自定义比较器
- 带自定义比较器的最小优先级队列
- 优先级队列自定义比较器
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 没有默认构造函数作为模板参数的自定义比较器
- set_intersection使用自定义设置比较器
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- 使用迭代器的自定义比较器函数
- Cython中带有自定义比较器的优先级队列
- gtest 期望无序元素与自定义比较器/匹配器一起使用
- 定义具有非标准签名的自定义映射比较器
- 为什么在类或结构中传递自定义比较器函数?
- 在priority_queue中使用默认容器但自定义比较器
- 是否有任何统一的方法可以在 c++ 中创建自定义比较器?
- C++ priority_queue与自定义比较器并删除任何项目
- 如何在 C++11 中将 std::max 与自定义比较器一起使用?
- 通过函数指针对类内的 STL SET 使用自定义比较器
- C#二进制编写器自定义
- QList 作为 qt 设计器自定义小部件中的一个属性
- std::sort - 正在传递错误的比较器未定义的行为