简体   繁体   中英

How i can create two-dimensional array in c++ with vector?

I want to create array mxn 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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM