如何解决错误:“operator<<”不匹配操作数类型是“std::ostream”{aka“std::basic_ostream<char>”}和“std::_List_iterator<int>”
std::less
我有一份该结构的清单
struct facefiguration{
int faceID;
list<int> setofVertices;
};
这里是我感到困惑的地方,我尝试在此处打印列表:
list<facefiguration> pattern;
这是完整的消息错误
void PrintFaces(){
currentFace = pattern.begin();
while(currentFace != pattern.end()){
cout << currentFace -> faceID << endl;
for(auto currentVertices = currentFace->setofVertices.begin(); currentVertices != currentFace->setofVertices.end(); currentVertices++){
cout << currentVertices;
}
cout << '\n';
currentFace++;
}
}
解决方法
我不认为错误消息真的属于导致问题的那一行(您之前是否尝试过 <<
-ing 列表本身?),但是
cout << currentVertices;
尝试使用 operator <<
引用(std::ostream
)和迭代器调用 std::cout
到 std::list
。这不起作用,因为迭代器类型没有这个运算符(为什么要)。然而,迭代器以指针为模型,因此允许取消引用以访问它们所引用的元素。长话短说;这应该有效:
cout << *currentVertices;
其中 *
前面的 currentVertices
是取消引用并产生一个 int&
(对基础列表元素的引用)。
currentVertices
是这里的迭代器。它是一个充当指针的对象。你不能用 cout
打印它。但是是的,您可以打印出迭代器指向的值。为此,您必须在迭代器之前放置一个 *
。也就是说,*currentVertices
。 (读作content of currentVertices
)
所以,总结是
-
currentVertices
是一个迭代器(或者你想说的指针),而*currentVertices
是content of that iterator
。 - 您需要
cout
content of iterator
而不是iterator
您已经得到了告诉您取消引用迭代器的答案:
for(auto currentVertices = currentFace->setofVertices.begin();
currentVertices != currentFace->setofVertices.end();
currentVertices++)
{
cout << *currentVertices; // dereference
}
但是,您可以使用基于范围的 for 循环自动执行此操作:
for(auto& currentVertices : currentFace->setofVertices) {
cout << currentVertices; // already dereferenced
}
,
正如其他人已经提到的
cout << currentVertices;
尝试打印迭代器。但是 operator<<
没有采用这种类型的第二个参数的重载。要么取消引用迭代器
// V
cout << *currentVertices;
或者简化整个循环:
for(const auto ¤tVertices : currentFace->setofVertices){
cout << currentVertices;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。