简体   繁体   中英

Java to C++ converting

In Java, we sometimes do this:

int [] foo = new int [5]

How do you do this in C++? I've put this in and it gave me an error.

std::vector<int> foo(5);

Don't use int[], this is ok if the size of your array is fixed (you do not need new, just

int a[5];

), but if it is variable, than it is a pain because you need to remember to disallocate it.

int *foo = new int[5];

This is how it is done without using any library, but you will have to manually delete that memory after you are done with it or else you have a memory leak

It is not recommended that you do it that way thought. You should use std::array if the size of the array will not change during its life time. If you want an array that can dynamic grow than you should use std::vector .

Use

int foo[5];

or

int *foo = new int[5];
...
delete []foo; // remember to release its memory afterwards!!!

or

#include <vector>
...
std::vector<int> foo(5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM