如何可靠地获得C样式数组的大小?通常推荐的方法似乎是使用sizeof,但它在传入x的foo函数中不起作用:
#include <iostream>
void foo(int x[]) {
std::cerr << (sizeof(x) / sizeof(int)); // 2
}
int main(){
int x[] = {1,2,3,4,5};
std::cerr << (sizeof(x) / sizeof(int)); // 5
foo(x);
return 0;
}this question的回答推荐sizeof,但他们并没有这么说(显然是这样?)如果您传递数组,则不起作用。那么,我是不是必须使用一个前哨呢?(我不认为我的foo函数的用户总是可以相信他们会在末尾放置一个标记。当然,我可以使用std::vector,但这样我就得不到很好的简写语法{1,2,3,4,5}了。)
发布于 2020-10-06 21:28:44
举个例子:
#include <iostream>
#include <type_traits>
int main()
{
int a[][3] = {{1, 2, 3}, {4, 5, 6}};
std::cout << "\nRank: : " << std::rank<decltype(a)>::value;
std::cout << "\nSize: [_here_][]: " << std::extent<decltype(a), 0>::value;
std::cout << "\nSize: [][_here_]: " << std::extent<decltype(a), 1>::value;
std::cout << "\nSize: [][]_here_: " << std::extent<decltype(a), 2>::value;
}打印:
等级::2大小:_here_:2大小::3大小:_here_:0
https://stackoverflow.com/questions/2404567
复制相似问题