Yadeses Yadeses - 2 months ago 12
C++ Question

Getting iterator for an array with a constant length in c++

I read on another stackoverflow post (variable length array error when passing array using template deduction) that the following should be possible:

#include <iostream>

int input() {
int a;
return a;

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

int sum[b];

Except that it doesn't seem to work, I still get an similar error.

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

Followed by information on possible templates it could fit.

Answer Source

You can use std::begin(sum) only when sum is regular array, not when it is a variable length array.

The following is OK.

const int b = 10;
int sum[b];

In your case, b is not known at compile time. For arrays whose length are not known at compile time, it's better to use std::vector instead of relying on a compiler specific extension. The following is OK.

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