在处理vector.size()时,c ++不合逻辑的> =比较很可能是由于size_type是无符号的 [英] c++ illogical >= comparison when dealing with vector.size() most likely due to size_type being unsigned
问题描述
在处理vector.size()又称为size_type
I could use a little help clarifying this strange comparison when dealing with vector.size() aka size_type
vector<cv::Mat> rebuiltFaces;
int rebuildIndex = 1;
cout << "rebuiltFaces size is " << rebuiltFaces.size() << endl;
while( rebuildIndex >= rebuiltFaces.size() ) {
cout << (rebuildIndex >= rebuiltFaces.size()) << " , " << rebuildIndex << " >= " << rebuiltFaces.size() << endl;
--rebuildIndex;
}
我从控制台中得到的是
And what I get out of the console is
rebuiltFaces size is 0
1 , 1 >= 0
1 , 0 >= 0
1 , -1 >= 0
1 , -2 >= 0
1 , -3 >= 0
如果我不得不猜测,我会说编译器盲目地将rebuildIndex强制转换为unsigned和+-,但是却导致事情表现得很奇怪,但是我真的不确定.有人知道吗?
If I had to guess I would say the compiler is blindly casting rebuildIndex to unsigned and the +- but is causing things to behave oddly, but I'm really not sure. Does anyone know?
推荐答案
正如其他人指出的,这是由于
C ++在比较具有不同值的值时会应用违反直觉的规则
签名该标准要求编译器将两个值都转换为
unsigned
.因此,通常认为最佳做法是
避免使用unsigned
,除非您要进行位操作(实际
数值无关紧要).遗憾的是,标准容器
不要遵循这种最佳做法.
As others have pointed out, this is due to the somewhat
counter-intuitive rules C++ applies when comparing values with different
signedness; the standard requires the compiler to convert both values to
unsigned
. For this reason, it's generally considered best practice to
avoid unsigned
unless you're doing bit manipulations (where the actual
numeric value is irrelevant). Regretfully, the standard containers
don't follow this best practice.
如果您以某种方式知道向量的大小永远不会溢出
int
,则只需将std::vector<>::size()
的结果强制转换为
int
并完成它.但是,这并非没有危险.作为马克
吐温说:不是你不知道会杀死你,而是你所杀死的
肯定知道这是不正确的."如果没有验证,何时
插入向量中,则更安全的测试将是:
If you somehow know that the size of the vector can never overflow
int
, then you can just cast the results of std::vector<>::size()
to
int
and be done with it. This is not without danger, however; as Mark
Twain said: "It's not what you don't know that kills you, it's what you
know for sure that ain't true." If there are no validations when
inserting into the vector, then a safer test would be:
while ( rebuildFaces.size() <= INT_MAX
&& rebuildIndex >= (int)rebuildFaces.size() )
或者,如果您真的不希望如此,并且准备中止,则准备放弃
发生时,设计(或查找)checked_cast
函数,然后使用它.
Or if you really don't expect the case, and are prepared to abort if it
occurs, design (or find) a checked_cast
function, and use it.
这篇关于在处理vector.size()时,c ++不合逻辑的> =比较很可能是由于size_type是无符号的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!