开发者

Compare with size_t, return int?

I'm writing some code examples from "How to Think Like a Computer Scientist in C++", and this one is about handling playing-card type objects and decks. I'm facing this situation:

int Card::find(const std::vector<Card>& deck) const {
    size_t deckSize = deck.size();
    for (size_t i=0; i<deckSize; i++)
        if (equals(*this, deck[i])) return i;

    return -1;
}

I couldn't use ".length()" on a vector in C++ in Visual Studio 2010 as in the text, and instead had to use .size() which returns (I believe) std::size_type. I figured I could use size_t and get away with it in order to avoid problems on different architectures, as I've been reading, but I'm wondering if I return i, but it's bigger than an integer, will I crash the program?

[Edited to be more specific in my question:] Once I start using vectors for larger things than cards, I considered using unsigned int because of a compiler mismatch warning, but I feel returning an unsigned int or int has a few issues: 1) int will not take a sufficiently large vector index. 2) returning unsigned int will not let me return -1. 3) unsigned int isn't equal to size_t on all architectures (I'm also doing microcontroller programming on an ARM Cortex-M3).

What should I d开发者_运维技巧o if I ever have a large enough vector?


Casting from size_t to int will not "crash" your program, but it's a bad bad practice. On the other hand, STL includes nice find algorithm for what you are doing.


int is 32 bit on 32 / 64 bit Windows and Linux. i will get truncated if greater than two at the 31st. you could use unsigned int and your program will be fine unless storing more than 4 G elements in the vector :)


size_t is typically an unsigned int but you can't rely on that. If it's bigger than an int you won't crash, you'll just overflow into a (probably negative) number.

Assuming you're not going to have several tens of thousands of cards in one vector, I'd be happy returning the int.


You can also return std::pair<size_t, bool>, similar to std::map insert(). Second template argument means success or fail.

If you ok with this, you could also use boost::optional

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜