0

I want to create array m x n with . My code:

    std::vector<std::vector<c_atom*>> new_lattice;

    new_lattice.resize(maxX);
    for (auto it : new_lattice) 
        it.resize(maxY);

    for(int i = 0; i<maxX; i++)
        for (int j = 0; j < maxY; j++)
        {
            c_atom *at = new c_atom;
            cout << new_lattice[i].size() << endl; // here i get 0. why?
            new_lattice[i][j] = at;
        }

but memory is not allocated for each array of new_lattice and I get size = 0 for each array of new_lattice. When I want to add pointer of atom in my array on position [i][j] i get error "array out of range". How i can solve this problem?

1 Answer 1

5

The problem is here:

for (auto it : new_lattice) 

The variable it will be a copy of the vectors inside new_lattice, you resize these copies instead of the original vectors.

The simple solution is to use references instead:

// Note ampersand for reference
//       v
for (auto& it : new_lattice) 

A possible better solution is to set the sizes already when defining the vectors:

std::vector<std::vector<c_atom*>> new_lattice(maxX, std::vector<c_atom*>(maxY));

And if the definition of new_lattice is made elsewhere, and the values of maxX and maxY isn't known until later, you can use assignment instead:

new_lattice = std::vector<std::vector<c_atom*>>(maxX, std::vector<c_atom*>(maxY));

Or possibly if new_lattice is a member variable inside a class, and maxX and maxY are passed as arguments to the constructor, then use a constructor initializer list:

TheClass(size_t maxX, size_t maxY)
    : new_lattice(maxX, std::vector<c_atom*>(maxY))
{
    // ...
}

Lastly a note on your use of pointers to c_atom: Is that really needed? Why not make a vector of vector of c_atom objects:

std::vector<std::vector<c_atom>> new_lattice(maxX, std::vector<c_atom>(maxY));

If you really need to use pointers (but nothing in the code or question indicates that need) then better use one of the smart pointers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.