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

Let me make a simple example:

Formula 1:

std::vector<int> vec;
// add 10E11 elements
for(std::size_t n = 0; n < vec.size(); ++n)
    // ...

Formula 2:

std::vector<int> vec;
// add 10E11 elements
for(std::vector<int>::size_type n = 0; n < vec.size(); ++n)
    // ...

Naturally, unsigned intor any unacceptable data types do not work here, and we must compile x64. My question is: is there any case where the first formulation can lead to problems, or can we safely always write it in this much shorter notation? I am also interested in similar settings if they are trivial to cover (x86, any other container, other applications size_type).

+4
source share
3 answers

std::vector , , vector::data " , [data(), data() + size()) ". , std::ptrdiff_t, std::size_t.

, [iterator.requirements.general]/6:

... n a (a + n), *(a + n) *(addressof(*a) + n)...

, vector::size_type std::size_t, 32 64- . , .

+4

, , . , std::vector<T>::size_type - , .

:

23.2.1 [container.requirements.general]

X:: size_type [is]

23.3.6.1 [vector.overview] §2

typedef implementation-defined size_type; // see 23.2
+3

Although std::vector::size_typeusually std::size_t, there is no guarantee that he should. Safer to use

for(std::vector<int>::size_type n = 0; n < vec.size(); ++n)
0
source

Source: https://habr.com/ru/post/1665967/


All Articles