std::end 如何知道数组的结尾? [英] How does std::end know the end of an array?
问题描述
std::begin
和 std::end
知道 container
或 array
的开始和结束>.
std::begin
and std::end
know the beginning and end of a container
or an array
.
例如,很容易知道 vector
的 end
和 begin
,因为它是一个提供此信息的类.但是,它如何知道像下面这样的 array
的结尾?
It so easy to know the end
and begin
of a vector
for example because it is a class that gives this information. But, how does it know the end of an array
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
并不难知道数组从哪里开始.但是它怎么知道它在哪里结束呢?常量整数 5
会存储在某个地方吗?
std::begin
is not that hard to know where the array start. But how does it know where it ends? Will the constant integer 5
be stored somewhere?
如果我能得到一些低级信息的答案,我将不胜感激.
I would appreciate if I got an answer with some low-level information.
推荐答案
常量整数 5 会存储在什么地方吗?
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] = { };
i
的类型是 int[5]
.Shafik 的回答谈到了如何使用这个长度来实现 end
.
the type of i
is int[5]
. Shafik's answer talks about how this length is used to implement end
.
如果你有 C++11,使用 constexpr
将是最简单的方法
If you've C++11, using constexpr
would be the simple way to go
template <typename T, size_t N>
inline constexpr size_t
arrLen(const T (&arr) [N]) {
return N;
}
如果您有一个 C++11 之前的编译器,其中 constexpr
不可用,则可能不会在编译时评估上述函数.所以在这种情况下,你可以使用这个:
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))
首先我们声明一个函数,返回对 N char
数组的引用,即 sizeof
这个函数现在是数组的长度.然后我们有一个宏来包装它,这样它在调用者端是可读的.
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.
注意:两个基类型相同但长度不同的数组仍然是两种完全不同的类型.int[3]
与 int[2]
不同.数组衰减,然而,在这两种情况下都会得到 int*
.如果您想了解更多信息,请阅读如何在 C++ 中使用数组?.
Note: Two arrays of the same base type but with different lengths are still two completely different types. int[3]
is not the same as int[2]
. Array decay, however, would get you an int*
in both cases. Read How do I use arrays in C++? if you want to know more.
这篇关于std::end 如何知道数组的结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!