c++ - C++ 中的比较函数错误:无效的比较器
问题描述
我做了一个简单的comaprison函数,如下所示:
bool function(int a, int b){
if (a % 2 == 0) {
return (a > b);
}
if (a % 2 == 1) {
return (a < b);
}
return false;
}
我的主要功能如下所示:
int main() {
vector<int> vector = {8, 4, 4, 8, 4, 1, 4, 4, 6, 10, 12 };
sort(vector.begin(), vector.end(), function);
cout << endl;
for (int i : vector) {
cout << i << " ";
}
return 0;
}
该函数应该排列一个数组,以便所有偶数都在数组的一部分中,而所有奇数都在该数组的另一部分中。
当我尝试运行代码时,它给了我错误“无效的比较器”。知道有什么问题吗?
解决方案
我假设您在std::sort
. 那么它必须满足比较的要求:
对于所有一个,
comp(a,a)==false
好的,您的比较器将始终返回false
相等的值。
如果
comp(a,b)==true
那时comp(b,a)==false
那一个失败了:
function(1, 2) == true
,所以 1 应该在 2 之前,但是...function(2, 1) == true
,所以 2 应该在 1 之前,哎呀。
如果
comp(a,b)==true
然后comp(b,c)==true
_comp(a,c)==true
那一个失败了:function(2, 1)==true
, function(1, 3)==true
, 但是function(2, 3)==false
。
此代码应该实现您想要的:
bool function(int a, int b){
if(a % 2 == b % 2) {
// If both are even or both are odd simply compare the numbers
return a < b;
}
else {
// if one is even and the other is odd then
// a should come before b if a is even
return a % 2 == 0;
}
}
排序[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
将导致[ 2, 4, 6, 8, 1, 3, 5, 7, 9, ]
推荐阅读
- innodb - 为什么 InnoDB 确实使用缓冲池,而不是 mmap 整个文件?
- prolog - Prolog 中的前 N 个斐波那契数
- php - create() 必须是数组类型(laravel 中的邮件陷阱错误)
- python - Is there a way to prevent an object in a list from printing more than once?
- arangodb - Arangodb:按时间戳和坐标过滤的自行车
- python - Instapy does not install
- macos - 如何在终端中读取 PLIST 文件中的特定值
- c - I have a bash script with a load of exports and a makefile. Is it possible to automatically create eclipse CDT project based on this information?
- nearprotocol - How do you generate a valid keypair for NEAR protocol from the command line?
- javascript - How to add a front-end framework (React, Vue, etc.) to SailsJS?