In addition to Helpers for Generic C++ Code Iterating Over Sequences the C++17 Standard Library provides the following helpers for writing generic code:
1 2 3 4 5 6 7 8 9 10 |
#include <iterator> // new helpers of C++17 are defined here template<class Container> void foo(Container& c) { // Generic way to obtain: auto data = std::data(c); // - data; auto empty = std::empty(c); // - flag of emptiness; auto size = std::size(c); // - size. } |
Function std::data()
provides access to the underlying raw data of:
- containers that have a member function
data()
; - instances of type type
std::initializer_list<T>
; - built-in arrays.
Function std::empty()
yields true
if either container or an instance of type std::initializer_list<T>
is empty. For built-in arrays the returned value is always false
because built-int arrays cannot be zero-sized according to the standard.
Function std::size()
returns a number of elements of:
- containers which are provides an iterator interface;
- built-in arrays.
Please note, that std::size()
eliminates the need of use the conservative way to calculate the number of elements of built-in arrays, i.e.:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iterator> // for std::size() void foo() { int numbers[10]; // Conservative way to calculate the number of elements of built-in arrays constexpr auto size1 = sizeof(numbers) / sizeof(*numbers); // Modern way to calculate the number of elements of built-in arrays constexpr auto size2 = std::size(numbers); static_assert(size1 == size2); } |
Finally, please note, that being used with containers these functions just calls the corresponding member functions: data()
, empty()
and size()
. Thus, for instance, std::size()
does not work with instances of type std::forward_list<T>
since this class doesn’t have the member function size()
by design.