Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 309
Analytiker Avatar asked Sep 05 '25 03:09

Analytiker


2 Answers

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.

like image 173
MRB Avatar answered Sep 08 '25 10:09

MRB


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.

like image 27
Sergey Kalinichenko Avatar answered Sep 08 '25 09:09

Sergey Kalinichenko