56

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
  • 2,145
  • 6
  • 33
  • 60
  • 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

114

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));
psiyumm
  • 6,437
  • 3
  • 29
  • 50
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • 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
  • 4
    @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
15

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
  • 464,522
  • 92
  • 875
  • 1,084