user2148758
user2148758

Reputation: 353

Handling int and std::vector::size_type in comparsion

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.

Upvotes: 2

Views: 643

Answers (1)

JVApen
JVApen

Reputation: 11317

Your code looks a bit too perfect for my taste.

Breaking it down:

const int res = std::stoi(cmdarg);
if (res >= 0 && static_cast<std::vector<MyClass*>::size_type>(res) < this->container.size())

The if-statement for checking below zero is nice. Personally I would write this as:

if (res < 0)
{
    std::cerr << "Negative number " << res <<" given for ..., a positive was expected" << std::endl;
    return -1;
}

This leads us to the cast:

auto unsigned_res = static_cast<std::vector<MyClass*>::size_type>(res);

However, size_type this vector always size_t as it uses the std::allocator. In code review, I would request to change this for readability to:

auto unsigned_res = static_cast<std::size_t>(res);

Finally, you can indeed nicely compare it:

if (unsiged_res < container.size())
    // Do something

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::stoi fails, see it's documentation

For more details on how to correctly deal with signed/unsigned, I can recommend this article on ithare.

Upvotes: 1

Related Questions