0
C++ array initialize?
How do you initialize an array without knowing the length? Like in a class for example: class arr { private: // initialize array here without length public: arr(int length){ // set array length here } } Iâm new to c++ and I donât really know how you would do this, also I donât want to use a vector.
5 Answers
+ 2
class arr {
private:
int *n; // declare int* pointer
public:
arr(int length){
n = new int[length]; // dynamically allocate memory by constructor.
}
}
+ 3
Why don't you want to use a vector?
+ 1
Also, you should free the array inside the destructor.
+ 1
ITDW
I don't think so. Vectors are more inefficient than arrays stored on the stack since they have to allocate memory on the heap, but you can't achieve what you want using static arrays anyways. You need to allocate on the heap, and you might as well let the vector class handle that for you.
Since you know the length beforehand, you can do something like this
class arr {
private:
std::vector<int> v;
public:
arr(int length) {
v.reserve(length)
}
};
This does the same thing that @Jayakrishna's code does, with the added advantage of the memory being allocated and freed automatically for you. Remember, you should avoid manual memory management as much as possible in C++.
0
I heard vectors are inefficient and i would rather use an array