yi*****@gmail.com wrote:
Hi,
In STL, can I create a variable size but non-growable array?
In Java, I can do this:
int[] void f (int size) {
int[] array = new int[size];
// do something with array
return array;
}
I guess I can use vector<> for that, but I don't need the array to be
growable, I just don't know the size upfront. So I am looking for a
more efficient data structure.
You could always do something like this:
template<typename T>
class array
{
T * arr;
int sz;
public:
array(int x) { arr = new T[x]; sz = x; }
~array() { delete [] arr; }
T & operator[](int i) { return arr[i]; }
int size() { return sz; }
};
That is of course a very simplistic version but it meets the stated
requirements and is relatively safe to use. You would want to add copy
and assignment ops to meet the rule of three but on the other hand this
class can be used as an array of sorts in a memcpy:
memcpy(&a1[0], &a2[0], a2.size() * sizeof(a2[0]));
But this is just as dangerous as doing so with your basic dyn array.
The benefit of using operators would be that you can do some checks and
throw up if the op would result in a buffer overrun. Also, passing by
value would be very ill advised without those operators; would result
in a crash.