Reputation: 312
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.
Upvotes: 0
Views: 2969
Reputation: 53319
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));
Upvotes: 1
Reputation: 9711
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 :
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
Upvotes: 2
Reputation: 854
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;
}
}
Upvotes: 0