Error C4018 with vector size () in C ++

im getting a warning when I use the .size () function with vectors in C ++ Here is a sample code:

vector<classname*> object; object.push_back(new classname2); for(int i=0;i<object.size();i++){ ....} 

I get a warning:

warning C4018: '<': signed / unsigned mismatch

I am not allowed to have any errors or warnings in my final code, so I need to get rid of this / find an alternative method, how can I get rid of this?

+6
source share
3 answers

The problem is that there is a potential (discontinuous) problem that can be incurred when working with unsigned comparisons. If you are on a 32-bit machine where the signed int is 4 bytes, it is possible that the size of the vector may exceed the maximum amount represented by this type. When this happens, you will receive a signed overflow and therefore Undefined Behavior.

Here are some alternatives you can use:

vector<T>::size_type :

 for (std::vector<classname>::size_type i = 0; i < object.size(); ++i); 

This is guaranteed to be correct, since it returns a type of size .

iterators

 std::vector<classname>::iterator it; for (it = object.begin(); it != object.end(); ++it); 

C ++ 11: Range for :

 for (auto& a : object) { // ... } 

std::size_t :

 for (std::size_t i = 0; i < object.size(); ++i); 

As doomster said in the comments, std::size_t will most likely be the bit size of your base platform.

unsigned int :

 for (unsigned int i = 0; i < object.size(); ++i); 

Note. Using this, you assume that size returns a 32-bit integer. This is usually not a problem, but you cannot be too sure; use any of the above methods if you can.

Another unique_ptr advice regarding your code is to use the unique_ptr / shared_ptr vector to facilitate memory management:

 std::vector<std::unique_ptr<classname>> object; 
+7
source

Vector size is always positive. Just use unsigned int as a loop variable:

 for (unsigned int i = 0; i < object.size(); i++) { ... } 

An even safer way is to declare a loop variable with size_t, which is the same as unsigned int on most platforms. But since this is the return type of the vector :: size () function, your counter variable will have the same range of values ​​as the possible size of the vector.

 for (size_t i = 0; i < object.size(); i++) { ... } 
0
source

Use unsigned iterator:

 for (unsigned int i = 0; i < object.size(); i++) { } 
-1
source

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


All Articles