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?
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.
std::vector<classname>::iterator it;
for (it = object.begin(); it != object.end(); ++it);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With