Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `size_t` always an alias for `vector<int>::size_type` or any other container type?

Tags:

c++

size-type

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).

like image 234
IceFire Avatar asked Jan 06 '17 08:01

IceFire


1 Answers

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 n and dereferenceable iterator values a and (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.

like image 167
Potatoswatter Avatar answered Nov 15 '22 06:11

Potatoswatter