Re: Array size determined at run time
paul@paullee.com wrote:
Hi all,
I'm trying to use an array in my C++ programme, but the size of the
array is not known until run time; I've tried using linked lists, which
work quite well, but traversing the list is quite slow. Is there
another way to declare an array during run-time? I thought about
something like:
iVal = some_function( blob );
MyClass *my_array;
my_array = new MyClass[ iVal ];
- but this doesn't want to work on my compiler.
IAW C++ standards, the std::vector should be your default container.
For most container requirements, std::vector is a better choice.
If you're not deleting or adding from/to the center of your container,
you don't need std::list, and should be using either std::vector or
std::deque.
As "Alf P. Steinbach" correctly stated, use std::vector.
std::vector<MyClass> myArray( iVal );
However, if your originally posted code doesn't compile, then I suspect
the vector code will not compile.
Your code will not compile if your class doesn't have a default
constructor.
If that's not the problem, please post specifics as to why it doesn't
compile, by posting your compile error.
-------------------------------------------------------------------
David Maisonave
Policy based smart pointers (http://axter.com/smartptr)
C++ Expert Exchange Member:
http://www.experts-exchange.com/Cplusplus
----------------------------------------------------------------------------------------