Obtaining a pointer to the end of an array
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.
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 have end()
already defined for me. If you ever need the array, it's available as &v[0]
.
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.
链接地址: http://www.djcxy.com/p/72988.html上一篇: 什么时候适合在C ++中使用静态(通过未命名的名称空间)?
下一篇: 获取指向数组末尾的指针