How to initialize a vector of vectors on a struct?

C++Vector

C++ Problem Overview


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));

C++ Solutions


Solution 1 - C++

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));

Solution 2 - C++

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.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionanat0liusView Question on Stackoverflow
Solution 1 - C++Joseph MansfieldView Answer on Stackoverflow
Solution 2 - C++Kerrek SBView Answer on Stackoverflow