Let's make the simplest example possible:
Formulation 1:
std::vector<int> vec;
// add 10E11 elements
for(std::size_t n = 0; n < vec.size(); ++n)
// ...
Formulation 2:
std::vector<int> vec;
// add 10E11 elements
for(std::vector<int>::size_type n = 0; n < vec.size(); ++n)
// ...
Naturally, unsigned int or any inappropriate data types do not work here and we have to compile x64. My question is: Is there any case in which the first formulation can lead to issues or can we safely always write it in this much shorter notation? I would also be interesting in similar settings if they are trivial to cover (x86, any other container, other applications of size_type).
std::vector guarantees that pointers are valid iterators for its entire sequence, because vector::data returns "A pointer such that [data(), data() + size()) is a valid range." That's pointer addition, which is defined over std::ptrdiff_t, which is the signed version of std::size_t.
Also, [iterator.requirements.general]/6 applies:
… for integral values
nand dereferenceable iterator valuesaand(a + n),*(a + n)is equivalent to*(addressof(*a) + n)…
It's possible for vector::size_type to be narrower than std::size_t, for example 32 bits on a 64-bit system. But it's not something I'd worry about.
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