Kill Unsigned / Signed Compare Error

In general, I want unsigned vs warnings to be signed.

However, in this particular case, I want it to be suppressed;

std::vector<Blah> blahs; for(int i = 0; i < blahs.size(); ++i) { ... 

I want to kill this comparison.

Thanks!

(using g ++)

+4
source share
1 answer

You must fix, not suppress. Use 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 use only i for iteration and do not need its value in a 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 blahs type. If your compiler supports a more complete subset of C ++ 11, do the following:

 for (auto& element : blahs) 

Which is the best.


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 it can be verbose, and every implementation that I know uses size_t as size_type .


If for some reason you really need a signed integer type for i , you will need to use:

 // 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) 
+12
source

Source: https://habr.com/ru/post/1308288/


All Articles