0

I would like to create a vector, and in each cell of this vector I would like to keep another vector which will contain a certain struct I defined. How am I supposed to do that? Am I supposed to define a pointer from each cell in the main vector to each of the other vectors (containing the structs I defined)? Am I supposed to access the memory where the vector is created using a pointer?

This is how I thought of doing it but I am honestly not really sure what I am doing:

vector<*vector> *vec = new vector<vector>

NOTE: I am a beginner in C++ and new to programming in general so go easy on me on this one fellas.

Thanks a lot

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111

3 Answers3

4

The general rule is don't use pointers (and dynamic allocation) unless you need to. So you can simply do this:

std::vector<std::vector<your_struct> > vector_of_vectors;
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1

Just like you would instantiate a vector of anything:

std::vector<std::vector<MyType>> v;

Pointers have nothing to do with it. You use a vector of pointers if and only if you need a vector of pointers.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

You don't need pointers, you can just use

std::vector<std::vector<int>> vec( 100 ); // create a vector of 100 vector<int> 
vec[42].push_back(1764); // add an element to the 43rd vector<int>
Daniel Frey
  • 55,810
  • 13
  • 122
  • 180