如何获取方法内部int数组(方法参数)的长度
How to get the length of a int array(method paramater) inside a method?
我的代码很简单:
#include <iostream>
using namespace std;
int test(int b[]){
cout<<sizeof(b)<<endl;
return 1;
}
int main(){
int a[] ={1,2,3};
cout<<sizeof(a)<<endl;
test(a);
system("pause");
}
该代码的输出为:
12
4
这意味着当a[]作为参数传递到函数test()时,is已经退化为int*,所以size(b)的输出是4,而不是12。所以,我的问题是,我如何才能在函数test[()中获得b[]的实际长度?
您可以使用一个函数模板:
#include <cstddef> // for std::size_t
template<class T, std::size_t N>
constexpr std::size_t size(T (&)[N])
{
return N;
}
然后
#include <iostream>
int main()
{
int a[] ={1,2,3};
std::cout << size(a) << std::endl;
}
注意,在C和C++中,int test(int b[])
是int test(int* b)
的另一种说法,因此test
函数内部没有数组大小信息。此外,您可以使用知道其大小的标准库容器类型,例如std::array
。
相关文章:
- c++方法参数只能在linux的发布模式下自行更改
- 使用移动语义:右值引用作为方法参数
- 无法将动态创建的对象数组从 qml 发送到 c++ 作为方法参数
- 将方法参数类型更改为子类中的派生类
- ofstream作为C 中的方法参数
- 使用 gmock 匹配器将 std::function 设置为 EXPECT_CALL 中的方法参数
- C com 方法参数扣除
- 获取非静态方法参数计数
- 使用 gmock 返回模拟方法参数
- 运行 QML 时出现"未知方法参数类型"错误
- 基本C - 构造contaning对象引用,并将其作为方法参数传递
- 将C 方法参数转换为模板参数会因编译错误而失败
- 如何在方法参数中使用boost :: asio :: buffer
- qsharedPointer作为方法参数或方法的返回值的良好实践
- 如何将方法指针声明为Typedef方法参数
- 方法参数中的 OpenCV 垫"预期")""
- 方法参数中的 consst* 常量
- 带有“class”详细类型说明符的方法参数
- 具有原始方法参数派生类的 C++ 重载方法参数
- C++ std::string length() 或 size() 不适用于方法参数