I need to dynamically allocate 1-D and 2-D arrays whose sizes are given at run-time.
I managed to "discover" std::vector
and I think it fits my purposes, but I would like to ask whether what I've written is correct and/or can be improved.
This is what I'm doing:
#include <vector> typedef std::vector< std::vector<double> > matrix; //... various code and other stuff std::vector<double> *name = new std::vector<double> (size); matrix *name2 = new matrix(sizeX, std::vector<double>(sizeY));
Vector are implemented as dynamic arrays with list interface whereas arrays can be implemented as statically or dynamically with primitive data type interface. Size of arrays are fixed whereas the vectors are resizable i.e they can grow and shrink as vectors are allocated on heap memory.
A vector is a dynamic array, whose size can be increased, whereas THE array size can not be changed. Reserve space can be given for vector, whereas for arrays you cannot give reserved space. A vector is a class whereas an array is a datatype.
Allocation of memory at the time of execution (run time) is known as dynamic memory allocation. The functions calloc() and malloc() support allocating of dynamic memory. Dynamic allocation of memory space is done by using these functions when value is returned by functions and assigned to pointer variables.
Dynamically allocated variables live in a piece of memory known as the heap, these are requested by the running program using the keyword "new". A dynamic variable can be a single variable or an array of values, each one is kept track of using a pointer.
Dynamically allocating arrays is required when your dimensions are given at runtime, as you've discovered.
However, std::vector
is already a wrapper around this process, so dynamically allocating vectors is like a double positive. It's redundant.
Just write (C++98):
#include <vector> typedef std::vector< std::vector<double> > matrix; matrix name(sizeX, std::vector<double>(sizeY));
or (C++11 and later):
#include <vector> using matrix = std::vector<std::vector<double>>; matrix name(sizeX, std::vector<double>(sizeY));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With