54

If I have a NxN matrix

vector< vector<int> > A;

How should I initialize it?

I've tried with no success:

 A = new vector(dimension);

neither:

 A = new vector(dimension,vector<int>(dimension));
anat0lius
  • 1,853
  • 5
  • 29
  • 55
  • 1
    You should probably consult an introductory book. new returns a pointer to what it has allocated (and is not needed here anyway). – Borgleader Feb 09 '14 at 18:46
  • vector> MyMatrix[4][4]; //works as well – Mich Jul 02 '15 at 20:12
  • 3
    This question is not a duplicate. The supposed linked duplicate is for a different question, for which the top answer also answers this question, but you won't find it when searching for this question. – smrdo_prdo Aug 19 '16 at 22:07

2 Answers2

112

You use new to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.

You have no reason to use new, since A is an automatic variable. You can simply initialise A using its constructor:

vector<vector<int> > A(dimension, vector<int>(dimension));
activatedgeek
  • 6,250
  • 3
  • 27
  • 48
Joseph Mansfield
  • 104,685
  • 19
  • 232
  • 315
  • Ok, I found my problem. I didn't mention that I have a pointed struct, which have that vector. And doing what u say: myStructVble->A(dimension, vector(dimension)); , it throws me "function doesn't match". – anat0lius Feb 09 '14 at 18:57
  • 3
    @LiLou_ You'll have to initialise it the struct's constructor. Or copy from a temporary to the member: `myStructVble->A = vector>(dimension, vector(dimension));` – Joseph Mansfield Feb 09 '14 at 19:00
14

Like this:

#include <vector>

// ...

std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));

(Pre-C++11 you need to leave whitespace between the angled brackets.)

Kerrek SB
  • 447,451
  • 88
  • 851
  • 1,056