微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

错误:“operator<<”不匹配操作数类型是“std::ostream”{aka“std::basic_ostream<char>”}和“std::_List_iterator<int>”

如何解决错误:“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::coutstd::list。这不起作用,因为迭代器类型没有这个运算符(为什么要)。然而,迭代器以指针为模型,因此允许取消引用以访问它们所引用的元素。长话短说;这应该有效:

cout << *currentVertices;

其中 * 前面的 currentVertices 是取消引用并产生一个 int&(对基础列表元素的引用)。

,

currentVertices 是这里的迭代器。它是一个充当指针的对象。你不能用 cout 打印它。但是是的,您可以打印出迭代器指向的值。为此,您必须在迭代器之前放置一个 *。也就是说,*currentVertices。 (读作content of currentVertices

所以,总结是

  1. currentVertices 是一个迭代器(或者你想说的指针),而 *currentVerticescontent of that iterator
  2. 您需要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 &currentVertices : currentFace->setofVertices){
    cout << currentVertices;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?