An example where std :: array :: max_size and std :: array :: size give different results

Whenever I try to execute max_size() and size() funtion std::array , I get the same results, I wanted to know if there could be a situation where two of them give different results.

+5
source share
5 answers

This function exists for compatibility with other containers, such as std::vector . For std::array these two values โ€‹โ€‹will always be the same.

+4
source

These two functions always return the same value, namely N for std::array<T, N> .

They are provided for consistency with other containers for which the values โ€‹โ€‹will differ (for example, std::vector ).

+4
source

There is no such example, since arrays are containers of a fixed size. Their current size is the same as their maximum size because they cannot grow or shrink.

The reason max_size() is to allow you to use std::array in a way that can be replaced with other containers from the C ++ standard library.

There is no reason to use max_size() in contexts when your program knows the container type std::array .

+4
source

std::array::max_size() returns the maximum number of elements that an array can ever hope to contain. The size of the array is a compile-time constant and part of its type. He can only ever hold just such a number of elements. The number of elements it contains and the number of elements it can contain are the same for std::array .

This particular function does not add much value to std::array , but it exists for compatibility with other containers, which can store a variable number of elements. Consider the case where a function template expects some type of container as an argument. You may be interested to know that the container capacity is maximum, and not std::array or another container.

+2
source

For std::array both functions are equal, as indicated in the documentation . Despite the duplication, std::array::max_size() exists, because std::array must satisfy the concept of Container , which requires such a method.

+1
source

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


All Articles