Compare with size_t, return int?

I am writing some code examples from "How to Think Like a Computer Scientist in C ++", and this concerns the processing of objects and decks of game cards. I came across a situation like this:

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 could not use ".length ()" for a vector in C ++ in Visual Studio 2010, as in the text, but instead had to use .size (), which returns (I believe) std :: size_type. I decided that I could use size_t and get away with it to avoid problems on different architectures, as I read, but I wonder if I will return i , but it is more than an integer, will I break the program?

[Edited more specifically in my question:] As soon as I start using vectors for larger things than maps, I considered using unsigned int due to warning compiler inconsistencies, but I feel that when I return unsigned int or int there are several problems: ) int will not accept a sufficiently large vector index. 2) returning unsigned int will not allow me to return -1. 3) unsigned int is not equal to size_t for all architectures (I also program the microcontroller on ARM Cortex-M3).

What if I have ever had a sufficiently large vector?

+4
source share
4 answers

Casting from size_t to int will not crash your program, but this is bad bad practice. STL, on the other hand, includes a good find algorithm for what you are doing.

+3
source

int 32 bit on 32/64-bit Windows and Linux. I get truncated if more than two on the 31st. you can use unsigned int, and your program will be great if more than 4 G elements are not stored in the vector :)

+2
source

size_t usually unsigned int , but you cannot rely on this. If it is larger than int , you won't crash, you just go to the (possibly negative) number.

Assuming you don't have tens of thousands of cards in one vector, I would be happy to return an int .

0
source

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

If you are ok with this, you can also use boost :: optional

0
source

Source: https://habr.com/ru/post/1332302/


All Articles