Search code examples
c++stlc++98size-tsize-type

std::size_t or std::vector<Foo>::size_type?


When I loop on a std::vector<Foo> (or every container having random access iterator) I use an unsigned integer variable i. If I want to respect the norm, should I use std::size_t or the type given by the container itself : std::vector<Foo>::size_type ?

If I chose std::size_t (for readability reasons), can I be sure that every implementation of every container in std namespace uses std::size_t as size_type ?

Note : I use C++98 only (for compatibility reasons).


Solution

  • It is not necessarily true that std::vector<Foo>::size_type is the same as std::size_t. This is true even for C++11.

    But personally I use std::size_t for a std::vector index irrespective of the type.

    You could always use a static assertion if you're feeling particularly diligent. Obviously static_assert is a later addition beyond what's in C++98, but in that standard you could use something like

    static char wrong_size_1[1 + sizeof(std::size_t) - sizeof(std::vector<Foo>::size_type)];
    
    static char wrong_size_2[1 - sizeof(std::size_t) + sizeof(std::vector<Foo>::size_type)];
    

    which would induce compile time failures if type types are not the same size.