OGeek|极客世界-中国程序员成长平台

标题: c++ - Define array, then change its size [打印本页]

作者: 菜鸟教程小白    时间: 2022-6-22 20:04
标题: c++ - Define array, then change its size

I come from a java background and there's something I could do in Java that I need to do in C++, but I'm not sure how to do it.

I need to declare an array, but at the moment I don't know the size. Once I know the size, then I set the size of the array. I java I would just do something like:

int [] array;

then

array = new int[someSize];

How do I do this in C++?



Best Answer-推荐答案


you want to use std::vector in most cases.

std::vector<int> array;

array.resize(someSize);

But if you insist on using new, then you have do to a bit more work than you do in Java.

int *array;
array = new int[someSize];

// then, later when you're done with array

delete [] array;

No c++ runtimes come with garbage collection by default, so the delete[] is required to avoid leaking memory. You can get the best of both worlds using a smart pointer type, but really, just use std::vector.






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4