Vector length

To get the length or count of total elements a std::vector array contains, std::vector provides a member function .size(). For example:

std::vector items{1, 2, 3};
std::cout << items.size() << "\n";

It should return 3.

C++17 also provides a non-member function std::size() that we can use to determine the length of any container. Eventually, std::size() only calls .size() member function for container classes. For example,

std::cout << std::size(items) << "\n";

It should return the same value 3.

size_type and std::size_t

size_type is the type value returned by .size() and std::size() functions. This is an alias for std::size_t which is again a typedef for a large unsigned integral type (mostly unsigned long, we can check using typeid().name()).

Note

It may be possible for size_type to be an alias for some other type depending upon the allocator std::vector is using.

size_type is a nested type member defined inside the container classes in containers library. For example,

std::vector<int>::size_type length{items.size()};

Tip

In C++23, We can define literal of type std::size_t by prefixing it with UZ. For example:

const auto somevalue{1UZ};

std::ssize() for C++20 and onwards

In C++20 and onwards, C++ provides std::ssize() non-member function which is same as std::size() but it returns a signed type, mostly std::ptrdiff_t. std::ptrdiff_t is often used as signed counterpart of std::size_t.

std::ptrdiff_t length{items.ssize()};

Indexing an array

Array container classes can be indexed (element accessing) using operator[]. The type of indexing value they take is size_type as mentioned above which is an unsigned integral value. Providing any signed integral gives a warning (if -Wsign-conversion flag is provided) for implicit conversion from signed to unsigned integral.

For example,

std::vector results{1, 2, 3, 4, 5};
for (int index{0}; index <= results.size(); ++index)
{
    std::cout << results[index];
}

Compiling it gives following warning:

simple_array.cpp:28:30: warning: conversion to 'std::vector<int, std::allocator<int> >::size_type' {aka 'long unsigned int'} from 'int' may change the sign of the result [-Wsign-conversion]
   28 |         std::cout << results[index];

We can solve this issue by using unsigned type std::size_t index that again has issues (discussed in issues with array indexing).

References

  1. https://www.learncpp.com/cpp-tutorial/stdvector-and-the-unsigned-length-and-subscript-problem/