Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ for-loop - size_type vs. size_t

Tags:

In the C++ Primer book, Chapter (3), there is the following for-loop that resets the elements in the vector to zero.

for (vector<int>::size_type ix = 0; ix ! = ivec.size(); ++ix)
ivec[ix] = 0;

Why is it using vector<int>::size_type ix = 0? Cannot we say int ix = 0? What is the benefit of using the first form on the the second?

Thanks.

like image 987
Simplicity Avatar asked Jan 31 '11 10:01

Simplicity


2 Answers

The C++ Standard says,

 size_type  |  unsigned integral type  |  a type that can represent the size of the largest object in the
allocation model

Then it adds,

Implementations of containers described in this International Standard are permitted to assume that their Allocator template parameter meets the following two additional requirements beyond those in Table 32.

  • The typedef members pointer, const_pointer, size_type, and difference_type are required to be T*,T const*, size_t, and ptrdiff_t, respectively

So most likely, size_type is a typedef of size_t.

And the Standard really defines it as,

template <class T> 
class allocator 
{
   public:
       typedef size_t size_type;
       //.......
};

So the most important points to be noted are :

  • size_type is unsigned integral, while int is not necessarily unsigned. :-)
  • it can represent the largest index, because it's unsigned.
like image 149
Nawaz Avatar answered Sep 20 '22 12:09

Nawaz


Yes you can use int, but only the type vector<int>::size_type guarantees that its type can be used to index all vector elements.

It may or may not be the same size as int. Eg, when compiling for 64-bit Windows, int is 32-bit wide, whereas vector<int>::size_type will be 64-bit wide.

Instead of using the rather verbose vector<int>::size_type, you could use std::size_t, as the former is a typedef for the latter. However, if you ever happen to change the container type, then its size_type maybe a different type, and you may have to modify your code if it uses std::size_t.

like image 24
Daniel Gehriger Avatar answered Sep 19 '22 12:09

Daniel Gehriger