错误:“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;
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...