So I have something like this (C++03):
class MyClass
{
// ...
}
class something
{
private:
std::vector<MyClass*> container;
// ...
}
// cmdarg can be anything, negative int too...
void something::foo(const std::string& cmdarg)
{
const int res = std::stoi(cmdarg);
if (res >= 0 && static_cast<std::vector<MyClass*>::size_type>(res) < this->container.size())
{
// ...
}
}
I would like to ask if the conversion from int to std::vector<MyClass*>::size_type is valid. The res >= 0 says it's non negative, so I guess converting to an another non-negative number is okey.
My problem is, if I write
if (res >= 0 && res < container.size())
I get a warning, because of comparsion with signed and unsigned integer types.
My above code (the full one) compiles and seems to work, but I'm not sure.
Thank you.
Your code looks a bit too perfect for my taste.
Breaking it down:
The if-statement for checking below zero is nice. Personally I would write this as:
This leads us to the cast:
However, size_type this vector always
size_tas it uses thestd::allocator. In code review, I would request to change this for readability to:Finally, you can indeed nicely compare it:
Note that I mentioned both the comparison and the cast, as this needs to happen in that order. On top of that, you also need some exception handling for when
std::stoifails, see it's documentationFor more details on how to correctly deal with signed/unsigned, I can recommend this article on ithare.