获得一个指向数组的结尾 [英] Obtaining a pointer to the end of an array

查看:109
本文介绍了获得一个指向数组的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的模板数组中的最后一个元素后获得一个指针指向:

 模板< typename的T,为size_t N'GT;
T * end_of(T(安培;数组)[N])
{
    返回数组+ N;
}

现在我好像记得,有一些问题,这种做法,但我不记得这是什么。我相信有一些东西需要与类型参数或功能参数的选择,但我不知道。因此,正如一个全面的检查,你看到上述code什么问题?使用小测试:

  INT测试[] = {11,19,5,17,7,3,13,2};
的std ::排序(测试,end_of(测试));


解决方案

您的建议是不是在编译的时候一定评估,这取决于优化。以下是在编译时计算的:

 模板< typename的T,为size_t N'GT; CHAR(安培;阵列(T(安培)[N]))[N];诠释的main()
{
  INT myArray的[10];  性病::法院LT&;<数组的sizeof(myarray的)LT;<的std :: ENDL;  返回0;
}

它的工作原理通过创建一个字符数组类型是相同数量的元素给定的数组中。 sizeof的总是字符数返回的大小。

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));

解决方案

Your proposal is not necessarily evaluated at compile time, it depends on optimisation. The following is calculated at compile time:

template <typename T, size_t N> char (&array(T(&)[N]))[N];

int main()
{
  int myArray[10];

  std::cout << sizeof array(myArray) << std::endl;

  return 0;
}

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.

这篇关于获得一个指向数组的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆