简体   繁体   English

杀死无符号/签名的比较错误

[英]kill unsigned / signed comparison error

In general, I want warnings of unsigned vs signed. 一般来说,我想要unsigned vs signed的警告。

However, in this particular case, I want it suppressed; 但是,在这种特殊情况下,我希望它被压制;

std::vector<Blah> blahs;

for(int i = 0; i < blahs.size(); ++i) { ...

I want to kill this comparison. 我想杀死这个比较。

Thanks! 谢谢!

(using g++) (使用g ++)

You should fix, not suppress. 你应该修复,而不是抑制。 Use an unsigned type: 使用无符号类型:

for (size_t i = 0; i < blahs.size(); ++i)

You can also use unsigned , but size_t is more appropriate here (and may have a different, larger, range). 您也可以使用unsigned ,但size_t在这里更合适(并且可能有不同的,更大的范围)。 If you're only using i to iterate and don't need its value in the loop, use iterators instead: 如果你只是使用i迭代并且在循环中不需要它的值,那么使用迭代器:

for (auto iter = blahs.begin(), end = blahs.end(); iter != end; ++iter)

If your compiler does not support auto , replace auto with T::iterator or T::const_iterator , where T is the type of blahs . 如果你的编译器不支持auto ,用T::iteratorT::const_iterator替换auto ,其中Tblahs的类型。 If your compiler supports a fuller subset of C++11, though, do this: 但是,如果您的编译器支持更完整的C ++ 11子集,请执行以下操作:

for (auto& element : blahs)

Which is best of all. 哪个是最好的。


Strictly speaking, the above is not "correct". 严格来说,上述不是“正确的”。 It should be: 它应该是:

typedef std::vector<Blah> blah_vec;
blah_vec blahs;

for (blah_vec::size_type i = 0; i < blahs.size(); ++i)

But this can be verbose, and every implementation I know uses size_t as size_type anyway. 但这可能很冗长,我知道的每个实现都使用size_t作为size_type


If for some reason you really need a signed integer type for i , you'll have to cast: 如果由于某种原因你真的需要一个有符号整数类型的i ,你将不得不施放:

// assumes size() will fit in an int
for (int i = 0; i < static_cast<int>(blahs.size()); ++i)

// assumes i will not be negative (so use an unsigned type!)
for (int i = 0; static_cast<size_t>(i) < blahs.size(); ++i)

// and the technically correct way, assuming i will not be negative
for (int i = 0; static_cast<blah_vec::size_type>(i) < blahs.size(); ++i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM