怎样的std ::知道到底数组的结束? [英] How does std::end know the end of an array?
问题描述
的std ::开始
和的std ::结束
知道容器
或阵列
。
这很容易知道结束
和开始
A 的载体
例如,因为它是一个类,给出了这样的信息。但是,它如何知道一个数组的结尾
像下面?
INT simple_array [5] {1,2,3,4,5};
汽车BEG =的std ::开始(simple_array);
汽车EN =的std ::结束(simple_array);
的std ::开始
是不是很难知道其中数组开始。但它是如何知道它在哪里结束?将不断的整数 5
存储在某个地方?
我想AP preciate如果我得到了一些低级别的信息的应答。
是恒定的整数5将存储一些地方?
块引用>是的,它是数组类型的一部分。但是,没有,这不是保存在某个地方明确。当你有
INT I [5] = {};
的类型i
是INT [5]
。沙菲克的这个长度是如何用来实现结束会谈的答案
。如果您已经C ++ 11,使用
constexpr
将是简单的方式去模板< typename的T,为size_t N'GT;
内嵌constexpr为size_t
arrLen(常量T(&安培; ARR)[N]){
返回N;
}如果你已经一个pre-C ++编译器11,其中
constexpr
不可用,上述功能可能无法在编译时进行评估。因此,在这种情况下,你可以使用这样的:模板< typename的T,为size_t N'GT;
CHAR(安培; arrLenFn(常量T(&安培; ARR)[N]))[N];#定义arrLen(ARR)的sizeof(arrLenFn(ARR))首先声明一个函数返回一个引用到N的阵列
字符
取值即的sizeof
这个功能现在想是该阵列的长度。随后,我们又一个宏来包装它,这样它在呼叫者的结束可读性。注意:相同的基本类型,但具有不同长度的两个阵列,仍然是两个完全不同的类型。
INT [3]
是不一样的INT [2]
。 阵列衰减,但是,会得到你一个为int *
在这两个案例。阅读我如何使用数组在C ++?的,如果你想知道更多。
std::begin
andstd::end
know the beginning and end of acontainer
or anarray
.It so easy to know the
end
andbegin
of avector
for example because it is a class that gives this information. But, how does it know the end of anarray
like the following?int simple_array[5]{1, 2, 3, 4, 5}; auto beg=std::begin(simple_array); auto en=std::end(simple_array);
std::begin
is not that hard to know where the array start. But how does it know where it ends? Will the constant integer5
be stored somewhere?I would appreciate if I got an answer with some low-level information.
解决方案is the constant integer 5 will be stored some where?
Yes, it's part of the type of the array. But no, it's not stored anywhere explicitly. When you have
int i[5] = { };
the type of
i
isint[5]
. Shafik's answer talks about how this length is used to implementend
.If you've C++11, using
constexpr
would be the simple way to gotemplate <typename T, size_t N> inline constexpr size_t arrLen(const T (&arr) [N]) { return N; }
If you've a pre-C++11 compiler where
constexpr
isn't available, the above function may not be evaluated at compile-time. So in such situations, you may use this:template <typename T, size_t N> char (&arrLenFn(const T (&arr) [N]))[N]; #define arrLen(arr) sizeof(arrLenFn(arr))
First we declare a function returning a reference to an array of N
char
s i.e.sizeof
this function would now be the length of the array. Then we've a macro to wrap it, so that it's readable at the caller's end.Note: Two arrays of the same base type but with different lengths are still two completely different types.
int[3]
is not the same asint[2]
. Array decay, however, would get you anint*
in both cases. Read How do I use arrays in C++? if you want to know more.这篇关于怎样的std ::知道到底数组的结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!