我有一个 list<Thing*> clothes
.我想打印出 things
到所需的格式:
+- shirt
+- pants
\\ shoes
所以除了最后一次迭代之外,基本上所有的输出都是相同的。到目前为止,我已经尝试过:
string CCloset::OutputContent() const {
string output;
for(auto i : this->clothes) {
if( next(i) == this->clothes.end() ) {
output.append("\\");
} else {
output.append("+-");
}
output.append( i->Output() );
}
return output;
}
理论是如果下一次迭代导致迭代器i
在list.end()
这意味着我们在最后一个元素,所以我们稍微修改输出。编译器说 Can't compare structures
.
next()
返回指向下一个元素的迭代器。在最后一个元素的情况下,它将指向列表的结尾。 list.end()
返回指向列表尾部的迭代器。
我错过了什么?
最佳答案
正如评论者已经指出的那样,i
不是迭代器,而是元素的值。
如果将循环修改为使用引用而不是值,则可以将当前元素的地址与最后一个元素的地址进行比较,如下所示:
for( const auto& i : this->clothes ) {
if( &i == &this->clothes.back() ) {
output.append("\\");
} else {
output.append("+-");
}
output.append( i->Output() );
}
关于c++ - 循环中列表的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43832379/