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 do 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 :)
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