C++ creating arrays

后端 未结 7 1108
一个人的身影
一个人的身影 2021-01-11 17:49

Why can\'t I do something like this:

int size = menu.size;
int list[size];

Is there anyway around this instead of using a vector? (arrays a

7条回答
  •  迷失自我
    2021-01-11 18:26

    first of all, vectors aren't significantly faster. as for the reason why you cant do something like this:

    the code will allocate the array on the stack. compilers have to know this size upfront so they can account for it. hence you can only use constants with that syntax.

    an easy way around is creating the array on the heap: int list = new int[size]; Don't forget to delete[] later on. However, if you use a vector and reserve the correct size upfront + compile with optimization, there should be little, to absolutely no overhead.

提交回复
热议问题