我想为currentDistance分配返回值CountBitDifference。相反,它返回给我0或1,具体取决于条件语句为假或真。有没有办法在条件语句中分配currentDistance值,否则我将不得不在其他地方执行此操作。
if (int currentDistance = CountBitDifference(m0.ptr<unsigned char>(matches[i].queryIdx),
m1.ptr<unsigned char>(matches[i].trainIdx),
cascadeSize, cascadeByteIndex) >= 8)
答案 0 :(得分:0)
您的代码会将currentDistance
初始化为>=
的结果。如果您要将从currentDistance
返回的值CountBitDifference
,和将该值与8进行比较 - 所有这些都在同一个表达式中 - 您将需要括号。
int currentDistance;
if ( ( currentDistance = CountBitDifference(m0.ptr<unsigned char>(matches[i].queryIdx),
m1.ptr<unsigned char>(matches[i].trainIdx),
cascadeSize, cascadeByteIndex)) >= 8)
或者,更清楚:
int currentDistance = CountBitDifference(m0.ptr<unsigned char>(matches[i].queryIdx),
m1.ptr<unsigned char>(matches[i].trainIdx),
cascadeSize, cascadeByteIndex);
if(currentDistance >= 8)
答案 1 :(得分:0)
首先,我会转储到日志以确认您的CountBitDifference表达式正在执行它应该执行的操作。如果是,似乎可能是一个奇怪的范围错误。在语句中分配currentDistance之前,它是否会杀死你定义和初始化currentDistance?
if语句也会检查此函数是否成功...你为什么要这样做?
编辑:我完全错过了表达式结尾处的比较。这有点kludgy,我会认真考虑将其分解为一个返回布尔值的函数。 8也是一个幻数。
编辑:试试这个,返回一个整数并作为一个函数来鼓励重复使用。
public int getBitDifference() {
//assumes you have declared your variables in a greater scope
//otherwise you will have to pass your variables to the function... hard to say
//without seeing all the code
return CountBitDifference(m0.ptr<unsigned char>(matches[i].queryIdx),
m1.ptr<unsigned char>(matches[i].trainIdx),
cascadeSize, cascadeByteIndex)
}
然后:
if (getBitDifference() >= 8) {
//do stuff here
}
更具可读性。同时将8声明为常量BIT_DISTANCE_MARGIN以避免使用幻数,所以
if (getBitDifference() >= BIT_DISTANCE_MARGIN) {
//do stuff here
}
你已经拥有了一些可读,可维护的代码。
答案 2 :(得分:0)
if (int currentDistance = CountBitDifference(m0.ptr<unsigned char>(matches[i].queryIdx),
m1.ptr<unsigned char>(matches[i].trainIdx),
cascadeSize, cascadeByteIndex) >= 8)
难以阅读。请尝试以下代码。
int currentDistance = CountBitDifference(m0.ptr<unsigned char>(matches[i].queryIdx)
,m1.ptr<unsigned char>(matches[i].trainIdx)
,cascadeSize, cascadeByteIndex);
if(currentDistance >= 8) { }
还要记住,当某人正在阅读您的代码时,可能是您以后的日期,他/您可能不记得=
和>=
运算符的关联性以及一个运算符的优先级。因此,将两个语句分成多行是个好主意。可读性很重要,不必要的简洁就是愚蠢。
答案 3 :(得分:0)
你不应该有任何理由要这样做......
在if语句之前初始化并且更易读。如果您不需要保留CountBitDifference的值,为什么不能这样做:
if (CountBitDifference(m0.ptr<unsigned char>(matches[i].queryIdx),
m1.ptr<unsigned char>(matches[i].trainIdx),
cascadeSize, cascadeByteIndex) >= 8)
如果您需要保留它,请执行以下操作:
int currentDistance = CountBitDifference(m0.ptr<unsigned char>(matches[i].queryIdx),
m1.ptr<unsigned char>(matches[i].trainIdx),
cascadeSize, cascadeByteIndex);
if (currentDistance >= 8)