2

I'm trying to do something like this:

int x=128, y=256;
std::vector<std::array<float,x*y>> codes;

Obviously this is wrong, while this is correct:

std::vector<std::array<float,128*256>> codes;

One solution to the first problem could be using macros like:

#define x 128
#define y 256
...
std::vector<std::array<float,x*y>> codes;

But I was wondering if there is another solution at run-time and not compile-time. Notice it's not necessary to use std::array, I need a std::vector of arrays (or whatever) of x*y elements.

justHelloWorld
  • 6,478
  • 8
  • 58
  • 138

1 Answers1

3

Try using const:

const int x = 128;
const int y = 256;
...
std::vector<std::array<float,x*y>> codes;

The problem in your first code was in the fact that x and y were not constants, so compiler could not rely on the fact that their values will not change in runtime and, consequently, was unable to determine the template argument value at compile-time.

alexeykuzmin0
  • 6,344
  • 2
  • 28
  • 51
  • 2
    Might I suggest `constexpr`? That way if you try to get `x` and `y` from runtime values, you'll get a compiler complaint at that point rather than when you instantiate `codes`. – user975989 Dec 06 '16 at 08:56
  • Voilà, it worked! Thanks! Anyway, since `x` and `y` are decided at run-time by the user, can we declare them without initializing them and do it in a second moment (when the user insert the value, i.e. 128 and 256)? – justHelloWorld Dec 06 '16 at 08:56
  • @user975989 Agree that `constexpr` is probably better here. Have no new compiler on hand to check. – alexeykuzmin0 Dec 06 '16 at 08:59
  • @justHelloWorld To create an array which size is unknown at compile-time, you cannot use `std::array`. Consider using `std::vector` instead. `std::vector` has a wonderful constructor which allows you to specify size and a value to fill: `vector> codes(size1, vector(size2, 0))`. – alexeykuzmin0 Dec 06 '16 at 09:01
  • @user975989 I'm sorry, can you try to explain again why `constexpr` should be better? First time that I see it! – justHelloWorld Dec 06 '16 at 09:05
  • @justHelloWorld Please read this: http://stackoverflow.com/questions/36405541/constexpr-vs-const-vs-constexpr-const – alexeykuzmin0 Dec 06 '16 at 09:07