gpt4 book ai didi

c++ - std::end 如何知道数组的结尾?

转载 作者:IT老高 更新时间:2023-10-28 12:50:05 25 4
gpt4 key购买 nike

std::beginstd::end 知道 containerarray 的开始和结束>.

例如,知道 vectorendbegin 非常容易,因为它是一个提供此信息的类。但是,它如何知道如下 array 的结尾?

int simple_array[5]{1, 2, 3, 4, 5};
auto beg=std::begin(simple_array);
auto en=std::end(simple_array);

std::begin 并不难知道数组从哪里开始。但是它怎么知道它在哪里结束呢?常量整数 5 会存储在某处吗?

如果我得到一些低级信息的答案,我将不胜感激。

最佳答案

But, how does it know the end of an array

它使用模板非类型参数来推断数组的大小,然后可以使用它来产生结束指针。 std::end 的 cppreference 部分的 C++11 签名如下:

template< class T, std::size_t N >
T* end( T (&array)[N] );

正如 hvd 所指出的,由于它是通过引用传递的,因此可以防止衰减到指针。

实现类似于:

template< class T, std::size_t N >
T* end( T (&array)[N] )
{
return array + N ;
}

Is the constant integer 5 will be stored some where?

5N 是数组类型的一部分,因此 N 在编译时可用。例如申请 sizeof到一个数组将给我们数组中的总字节数。

很多时候我们看到一个数组通过值传递给一个函数。在这种情况下,数组 decays to a pointer类型存储在数组中。所以现在尺寸信息丢失了。通过引用传递可以让我们避免这种信息丢失并从类型中提取大小N

关于c++ - std::end 如何知道数组的结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33496322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com