开发者

kill unsigned / signed comparison error

In general, I want warnings of 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 comp开发者_运维百科arison.

Thanks!

(using 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). If you're only using i to iterate and don't need its value in the loop, use iterators instead:

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. If your compiler supports a fuller subset of C++11, though, do this:

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.


If for some reason you really need a signed integer type for i, you'll have to cast:

// 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜