Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error C4018 with vector size() in c++

Tags:

c++

im getting a warning when i use the function .size() with vectors in c++ Heres a sample code:

vector<classname*> object;
object.push_back(new classname2);

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

i get the warning:

warning C4018: '<' : signed/unsigned mismatch

I'm 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?

like image 991
Eduardo Avatar asked May 05 '13 17:05

Eduardo


1 Answers

The problem is that there is a potential (breaking) issue that one can incur when dealing with signed-to-unsigned comparisons. If you're on a 32-bit machine where a signed int is 4 bytes, it could be possible that the size of the vector could exceed the maximum quantity representable by that type. When that happens, you get signed overflow and consequentially Undefined Behavior.

Here are a few alternatives you can uses:

vector<T>::size_type:

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

This is guaranteed to be correct as it is the type the size returns.

Iterators

std::vector<classname>::iterator it;

for (it = object.begin(); it != object.end(); ++it);

C++11: Range-based 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 is likely to have the bit-size of your underlying platform.

unsigned int:

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

Note: By using this, you're assuming that size returns a 32-bit integer. Generally this isn't a problem, but you can't be too sure; use any of the above if you can.

Another tip relative to your code is to use a vector of unique_ptr/shared_ptr to facilitate memory-management:

std::vector<std::unique_ptr<classname>> object;
like image 103
David G Avatar answered Nov 02 '22 01:11

David G