Kang_HM
Kang_HM

Reputation: 13

Problem: 2d Vector (nested Vector) with datatype of new class

I made 2 classes, one of them is "Cells" and another one is "Calculation".

cells is a 2d vector with a datatype of class "Cells" and i want to put the object of "Cells" - content of the Cell - in a 2d vector "Cells"

later i will calculate matrixPotential and deltaMatrixPotential.

but i even cannot put the object in a 2d Vector.

Cells::Cells(double matrixPotential,
             double deltaMatrixPotential)
{
    this->matrixPotential = matrixPotential;
    this->deltaMatrixPotential = deltaMatrixPotential;
}

Calculation::Calculation()
{
    std::vector<std::vector<Cells> > cells;

    for(unsigned long i = 0; i < size; i++){
        for(unsigned long j = 0; j < size; j++){
            Cells contentOftheCell(matrixPotential,
                                   deltaMatrixPotential);
            cells[i][j] = contentOftheCell;
        }
    }
}

How can i make it possible? I could do it in a normal vector but it seems impossible in a 2d Vector

Upvotes: 0

Views: 48

Answers (1)

Mark Storer
Mark Storer

Reputation: 15870

You need to allocate to your vectors, not just write to them hoping there is something there on which to write.

std::vector<std::vector<Cells> > cells;
cells.resize(size);

for(unsigned long i = 0; i < size; i++) {
    cells[i].resize(size)
    for(unsigned long j = 0; j < size; j++) {
        Cells contentOftheCell(matrixPotential,
                               deltaMatrixPotential);
        cells[i][j] = contentOftheCell;
    }
}

This example allocates the memory via resize, which is more efficient than using vector::push_back to add space as you go. It's possible to Properly Construct your vectors in the first place which would be a bit better, but I leave that as an exercise for the reader.

Upvotes: 1

Related Questions