如何将数组的大小设置为与向量的大小相等。这是我的代码:
vector<Point> data_obj;
int my_array[data_obj.size()]
Run Code Online (Sandbox Code Playgroud)
但我收到编译错误说:
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
Run Code Online (Sandbox Code Playgroud)
我不明白这个错误。你能提供一些解释吗?
正如错误所说,静态数组的大小在编译时必须是恒定的。这是可能的的大小std::vector可以在运行时改变,所以该阵列的尺寸是不能保证恒定的。你必须制作一个动态数组
int* my_array = new int[data_obj.size()];
Run Code Online (Sandbox Code Playgroud)
然后记得删除它
delete[] my_array;
Run Code Online (Sandbox Code Playgroud)