Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allocating vectors (or vectors of vectors) dynamically

Tags:

c++

vector

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)); 
like image 580
Federico Avatar asked Jul 21 '11 11:07

Federico


People also ask

Is vector dynamically allocated?

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.

Why would we use dynamically allocated arrays vs vectors?

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.

What is dynamically allocated?

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.

What is dynamically allocated variable?

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.


1 Answers

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)); 
like image 125
Lightness Races in Orbit Avatar answered Nov 12 '22 07:11

Lightness Races in Orbit