获取指向数组末尾的指针
我使用以下模板来获取指向数组最后一个元素之后的指针:
template <typename T, size_t n>
T* end_of(T (&array)[n])
{
return array + n;
}
现在我似乎记得这种方法存在一些问题,但我不记得它是什么。我相信它与类型参数或函数参数的选择有关,但我不确定。那么,作为健全性检查,您发现上述代码有任何问题吗?小使用测试:
int test[] = {11, 19, 5, 17, 7, 3, 13, 2};
std::sort(test, end_of(test));
I use the following template to obtain a pointer pointing after the last element of an array:
template <typename T, size_t n>
T* end_of(T (&array)[n])
{
return array + n;
}
Now I seem to remember that there was some problem with this approach, but I cannot remember what it was. I believe it had something to with the choice of the type parameters or function parameters, but I'm not sure. So just as a sanity check, do you see any problems with the above code? Small usage test:
int test[] = {11, 19, 5, 17, 7, 3, 13, 2};
std::sort(test, end_of(test));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的建议不一定在编译时进行评估,它取决于优化。以下是在编译时计算的:
它的工作原理是创建一个 char 类型的数组,该数组的元素数量与给定数组的元素数量相同。 sizeof 始终返回大小(以字符数为单位)。
Your proposal is not necessarily evaluated at compile time, it depends on optimisation. The following is calculated at compile time:
It works by creating an array type of char which is the same number of elements as the given array. sizeof always returns size in number of chars.
我看到的唯一问题是,如果您在编译时不知道长度,您的模板将不知道要在其中放置什么。所以你必须说
test+x
或者其他什么,现在你有两种不同的方法来做同样的事情。就我个人而言,我宁愿只使用
vector
,因此已经为我定义了end()
。如果您需要该数组,可以使用&v[0]
形式获取。The only problem i see is that if you ever don't know the length at compile time, your template won't know what to put in there. So you'd have to say
test+x
or something anyway, and now you have two different ways to do the same thing.Personally i'd rather just use a
vector<int>
and thus haveend()
already defined for me. If you ever need the array, it's available as&v[0]
.你还需要一个 const 版本。然而,据我所知,这种方法没有实际问题——我发现它被广泛使用。
You need a const version too. However, as far as I know, there's no actual problems with that approach- I see it used commonly.