作者:小晶晶妮妮宝贝 | 来源:互联网 | 2023-05-18 14:34
std::beginandstd::endknowthebeginningandendofacontaineroranarray.开始和结束知道容器或数组的开始和结束。
std::begin
and std::end
know the beginning and end of a container
or an 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
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?
开始并不难知道数组从哪里开始。但它如何知道它的终点呢?常数整数5会被存储在某处吗?
I would appreciate if I got an answer with some low-level information.
如果我能得到一些低层次的信息,我将不胜感激。
3 个解决方案
22
is the constant integer 5 will be stored some where?
常数整数5会被存储在什么地方?
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
is int[5]
. Shafik's answer talks about how this length is used to implement end
.
i的类型是int[5]。沙菲克的回答谈到了如何使用这个长度来实现end。
If you've C++11, using constexpr
would be the simple way to go
如果您有c++ 11,那么使用constexpr将是最简单的方法
template
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:
如果您有一个前c++ 11编译器,其中constexpr不可用,那么上面的函数可能不会在编译时进行计算。所以在这种情况下,你可以用这个:
template
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.
首先,我们声明一个函数返回一个对N个字符的数组的引用,例如,这个函数的sizeof现在是数组的长度。然后我们有一个宏来包装它,这样它在调用者的端是可读的。
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.
注意:两个基类型相同但长度不同的数组仍然是两个完全不同的类型。int[3]不同于int[2]。然而,在这两种情况下,数组衰变都会使您得到int*。阅读如何在c++中使用数组?如果你想知道更多。