Analytiker
Analytiker

Reputation: 61

Vector index variable declaration (size_t or std::vector<DATATYPE>::size_type)

What is the best practice for declaring a new variable for comparison with the size of a vector? which of the following should we favor (i.e. vector of doubles)?

  1. uint compareVar;
  2. std::uint64_t compareVar;
  3. std::size_t compareVar;
  4. std::vector<double>::size_type compareVar; // how is this different than size_t?

and why?

Upvotes: 4

Views: 894

Answers (3)

eerorika
eerorika

Reputation: 238361

In order of "goodness": 4 3 1 2.

std::vector::size_type is an implementation defined unsigned integer type that is guaranteed to be able to index all elements in any vector. It is good to use this, because it is guaranteed to be at least as large as is needed in all cases, but is not required to be any larger than that.

std::size_t is an implementation defined unsigned integer type that is guaranteed to be able to represent the size of any object. std::vector::size_type is typically same as this, but that is not guaranteed in theory.

uint There is no such type in C++, but I assume that you mean unsigned. This is not guaranteed to be able to represent all indices of a vector. In fact, on 64 bit systems which are ubiquitous, largest representable value of unsigned is often much much less than largest possible vector. Still, if you know that the upper limit is much less in your program, then using this is probably fine... as long as that assumption never changes.

std::uint64_t is an unsigned type that is not guaranteed to exist on all systems, and is not guaranteed to be sufficiently large to represent all indexes of a vector, although it is likely be sufficient on 64 bit systems and those with even smaller address space, which essentially covers nearly all computers at the moment.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

If you need an equality or ordinal comparison only, the best type would be the one used by vector's implementation, meaning

std::vector<MyType>::size_type compareVar

This guarantees that the type you use matches the type of vector's implementation regardless of the platform.

Note that since the type is unsigned, computing the difference between vector's size and compareVar would require some caution to avoid incorrect results when subtracting a larger value from a smaller one.

Upvotes: 1

MRB
MRB

Reputation: 3822

The one that you must use is std::vector::size_type. it is usually std::size_t but standard doesn't specify it. it is possible one implementation uses another type. You should use it whenever you want to refer to std::vector size.

uint, uint64_t and even size_t must not be used because in every implementation and platform the underlying vector implementation may use different types.

Upvotes: 4

Related Questions