c++vectortype-conversionsize-type

What does size_type in the constructor of vector mean?


The specification for the constructor of vector I am using is:

vector(size_type count, const T& value, const Allocator& alloc = Allocator());

I am trying to initialize a vector, and I am not very familiar with size_type. Both cplusplus and cppreference don't have an entry for size_type. A quick Google tells me it is some kind of data type for representing sizes, capacity etc. for things like containers (I think). I'm still not very sure if I'm understanding it correctly or how to use it though.

Let's say I wish to initialise an int vector of count (10*n/3) + 1 where n is of type int. Can I cast count as type long? Am I even doing it right? How do I understand and use size_type?

Please ignore hardware considerations like whether the computer can even assign enough memory in the first place. I'll worry about that later, for now I just want to focus on understanding this concept.


Solution

  • It's a typedef defined inside std::vector; it's actually a synonym for std::size_t, which, in turn, is a typedef for an implementation-defined unsigned integer type capable of holding the size of the biggest object that is possible to create on the current machine. In practice, you can think of it as some kind of unsigned integer, which is always used throughout the std::vector interface when referring to an index or an element count.

    On "regular" machines (where you have 32 bit integers) and if you are not hitting the limits of "regular" ints in your code for elements counts you can use int for indexes without problems (and you are actually safer from subtle bugs that arise from arithmetic/comparisons on unsigned integers).