简体   繁体   中英

How to set objects in 2D vector to null pointer [C++]

Imagine

std::vector<std::vector<Objekt>> m_pole;

We want to set every object to nullptr. But following code produces 2 errors. Vars row and col are not declared.

    std::vector<std::vector<Objekt>>::std::iterator row;
    std::vector<Objekt>::std::iterator col;

    for(row = m_pole.begin(); row != m_pole.end(); row++) {
        for(col = row->begin(); col != row->end(); col++) {
            m_pole[row][col] = nullptr;
        }
    }

Any ideas how to solve this problem ? Thanks for answers, MK.

You seem to confuse multiple things.

First: you have a vector of vectors of objects. That's good! However, it's objects, not pointers (again that's good), therefor it can not be null, as only pointers can be null (one last time, this is good, no invalid memory access, null pointer exceptions…). If you want to handle optional elements, you have to decide between different strategies :

  1. Not inserting them in your structure
  2. using pointers and setting them to null (if you do that, please use smart pointers)
  3. using boost::optional

Secondly: you are confusing pointers and indexes

std::vector<std::vector<Objekt>>::iterator row_it; // where does this std came from ?
std::vector<Objekt>::iterator element_it; // the iterator points to an element

for(row_it = m_pole.begin(); row_it != m_pole.end(); ++row_it) { // Get the habit to pre-increment
    for(element_it = row_it->begin(); element_it != row->end(); ++element_it) {
        *element_it = nullptr; // This won't work, as it's an object, not a pointer
    }
}

Thirdly: c++11 has nice iterators (other wise use BOOST_FOREACH) :

for(auto & row : m_pole) // reference is importante !
    for(auto & element : row)
        element = nullptr; // again, can't work because it's an object

You're mixing up iterators and indices. Iterators are dereferenced using the * operator.

for(row = m_pole.begin(); row != m_pole.end(); row++) 
{
  for(col = row->begin(); col != row->end(); col++)
    *col = nullptr;
}

This is assuming that Objekt is a typedef for a pointer or it has an assignment operator that can take nullptr . Otherwise you'll need to use Objekt*

But you can save yourself the trouble of writing an initialization loop and just use the std::vector constructor.

std::vector<std::vector<Objekt> > m_poles(numrows, std::vector<Objekt>(numcols, nullptr));

You should use pointer:

std::vector<std::vector<Objekt*>> m_pole;
std::vector<std::vector<Objekt*>>::std::iterator row;
std::vector<Objekt*>::std::iterator col;

for(row = m_pole.begin(); row != m_pole.end(); row++) {
    for(col = row->begin(); col != row->end(); col++) {
        *col = nullptr;
    }
}

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