是否有类似std :: size()的函数? [英] Is there some function like std::size()?
问题描述
给出任意类型T的内置数组x,其中有函数 std :: begin()
和 std :: end()
我可以打电话给我,但是为什么没有 std :: size()
?
Given a builtin array x of arbitrary type T, there are functions std::begin()
and std::end()
that I can call, but why isn't there a std::size()
? Seems odd not to have that.
我可以使用 std :: end(x)-std :: begin(x)
,但仍然是 std :: size(x)
会更好。
I could use std::end(x)-std::begin(x)
, but still a std::size(x)
would be better.
是的,我知道 std :: vector
和 std :: array
类中的一个。这只是一个问题,为什么STL中尚不存在如此简单的内容。
Yes, I know of the std::vector
and std::array
classes. This is just a question of why something as simple as this isn't available as yet in the STL.
推荐答案
c $ c> std :: extent ,将应用于数组的 type :
There's std::extent
, which is to be applied to the type of the array:
#include <type_traits>
int a[12];
assert(std::extent<decltype(a)>::value == 12);
或者您可以使用 std :: distance(std :: begin(a ),std :: end(a))
。
前者显然是一个常量表达式,但实际上后者可以静态计算
The former is manifestly a constant expression, though in practice the latter can be comuted statically as well.
最后,总有本地解决方案:
Finally, there's always the homegrown solution:
template <typename T, std::size_t N>
constexpr std::size_t array_size(T const (&)[N])
{ return N; };
这篇关于是否有类似std :: size()的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!