想象
std::vector<std::vector<Objekt>> m_pole;
我们想将每个对象设置为 nullptr。但是下面的代码会产生 2 个错误。 Vars row 和 col 未声明。
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;
}
}
有什么办法解决这个问题吗? 感谢您的回答,MK。
最佳答案
你似乎混淆了很多东西。
首先:您有一个由对象 vector 组成的 vector 。那挺好的!然而,它是对象,而不是指针(同样很好),因此它不能为空,因为只有指针可以为空(最后一次,这很好,没有无效的内存访问,空指针异常......)。 如果你想处理可选元素,你必须在不同的策略之间做出决定:
- 不将它们插入您的结构
- 使用指针并将它们设置为空(如果这样做,请使用智能指针)
- 使用 boost::optional
其次:你混淆了指针和索引
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
}
}
第三:c++11 有很好的迭代器(否则使用 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
关于c++ - 如何将二维 vector 中的对象设置为空指针 [C++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14025393/