18881

how can to allocate a matrix using vector on the heap

Question:

hey, i am trying to allocate a dynamic matrix on the heap and seems like i am doing something wrong. i try to do the following thing : vector< vector<int*> >* distancesMatrix=new vector< vector<int*> >;<br /> it does allocate a matrix on the heap but the matrix itself is empty, i want the matrix to be sizeXsize but cant sort it alone when not trying to allocate it on the heap with using vector<vector<Distance*> > distance(size+1, vector<Distance*>(size+1, NULL)); thanks for your help

Answer1:

Try vector< vector<int> >(size, size).

Answer2:

A std::vector keeps its data on the heap, even if the object itself is on the stack. I cannot imagine a scenario where you want a std::vector itself to be on the heap. Do this:

vector< vector<int> > distancesMatrix;

and you're done.

That said, it might be better to wrap multi-dimensional class around a one-dimensional vector than nesting vectors.

Answer3:

I would suggest not using the vector-of-vectors approach for two reasons:

1) it allows the resulting data to be jagged (that is, any two rows may be different lengths). If you are wrapping this in a external interface or you just don't care, that may not be a problem, but:

2) the elements of the "matrix" are not going to be contiguous in memory, which can have a performance impact due to cache locality, reallocations, extra memory being used, et cetera. It may not be a big impact, but it's there.

Instead I would suggest you do this:

std::size_t size = 4; // Whatever you prefer. std::vector<int> matrix( size * size );

You can then access the element at (x,y) using the following idiom:

int element = matrix[ x + y * size ];

The vector will allocate its elements on the heap, and they will be contiguous and this will also ensure the matrix is rectangular. You may want to wrap this in a class to provide a more natural interface.

If you really want to put the "matrix" itself on the heap, you can do so by making it a pointer and allocating it with new (or better, if you've wrapped the vector into your own class, say one called Matrix, put <em>that</em> on the heap instead).

Answer4:

Try:

#include <vector> int main() { // Initialize the outside vector with 20 copies of a vector that contains 20 integers that are zero initialized. std::vector<std::vector<int> > data(20, std::vector<int>(20)); data[10][10 = 5; }

Recommend

  • Using numpy.unique on multiple columns of a pandas.DataFrame
  • How to read csv file into an Array of arrays in scala
  • Doctrine DQL returning flat array from join
  • Fold function in Octave
  • C# foreach - Is collection computed with each iteration? [duplicate]
  • draw pie chart using iOS quartz 2D
  • How to fallback to entirely different index page if user has javascript disable?
  • Best HTML5 structure for a layout where the title/header is outside the article tag
  • Returning this from a constructor function in JS
  • How to make SASS put relative paths in its output
  • Spring security - same page to deliver different content based on user role
  • Slicing an SPA into several components and use AngularJS
  • How do I add a File Type Association in a Windows Phone 8.1 app manifest?
  • runtime-check whether an instance (Base*) override a parent function (Base::f())
  • Where these are stored?
  • Building Qt project for C++11 standard
  • C++ friend class std::vector
  • Error in installing package: fatal error: stdlib.h: no such file or directory
  • how do i write assembly code from c#?
  • Sequential (transactional) API calls in angular 4 with state management
  • How can I sort a a table with VBA with given text condition?
  • Display images in Django
  • Problem deserializing objects from cache on MyBatis 3/Java
  • Allowing both email and username for authentication
  • Handling un-mapped Rest path
  • what is the difference between the asp.net mvc application and asp.net web application
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Calling of Constructors in a Java
  • AT Commands to Send SMS not working in Windows 8.1
  • Cannot Parse HTML Data Using Android / JSOUP
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • How do I configure my settings file to work with unit tests?
  • Java static initializers and reflection
  • embed rChart in Markdown
  • Is it possible to post an object from jquery to bottle.py?
  • unknown Exception android
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • Observable and ngFor in Angular 2
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app