在下面的代码中,我需要获取 std::array
的大小作为函数参数。我更喜欢 std::array
而不是 std::vector
因为容器的大小不应该改变。但是,编译器会报错 error: ‘n’ is not a constant expression
。如何通过函数参数获取数组的大小?
main.cpp:
#include <iostream>
#include <array>
using namespace std;
void fnc(const int n)
{
array<int,n> a;
}
int main()
{
fnc(5);
return 0;
}
最佳答案
你不能。数组的大小必须是常量表达式——这意味着它必须在编译期间已知。如果它是函数参数,则不可能,因为可以使用任何参数调用该函数。使用 std::vector - 您很可能看不到任何性能差异。
关于c++ - 获取 std::array 的第二个参数(大小)作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24768574/