2017-08-22 51 views
-1

阵列获取迭代器我读了另一个计算器后(variable length array error when passing array using template deduction),下面应该是可能的:与C++中的固定长度

#include <iostream> 

int input() { 
    int a; 
    std::cin>>a; 
    return a; 
} 

int main() 
{ 
    const int b = input(); 

    int sum[b]; 
    std::begin(sum); 
} 

除了它似乎并没有工作,我仍然得到类似的错误。

In function 'int main()': 
16:17: error: no matching function for call to 'begin(int [b])' 
16:17: note: candidates are: 

后面跟着可能的模板信息。

+0

'#include '。但是,不要使用C风格的数组 - 所以'#include '代替。 – LogicStuff

+0

'input()'不是一个常量表达式。 – Rakete1111

+0

'#包括'没有解决它。是否有可能使cin的结果保持不变?我想它是切换到矢量比。 – Yadeses

回答

1

只有当sum是常规数组时,才可以使用std::begin(sum),而不是当它是可变长度数组时。

以下是确定的。

const int b = 10; 
int sum[b]; 
std::begin(sum); 

在你的情况下,编译时不知道b。对于编译时不知道长度的数组,最好使用std::vector而不是依赖于编译器特定的扩展。以下是确定的。

const int b = input(); // You can use int b, i.e. without the const, also. 
std::vector<int> sum(b); 
std::begin(sum);