error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘std::_List_iterator<int>’)

error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘std::_List_iterator<int>’)

你好,我正在尝试打印一个整数列表,但我一直收到这个错误。

我有一个结构,上面有一个列表。

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++;
      }

    }

这是完整的消息错误

error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘std::__cxx11::list<int>’)

我不认为错误消息真的属于导致此处问题的行(您之前是否尝试过 <<-ing 列表本身?),但是

cout << currentVertices;

尝试使用 std::ostream 引用(std::cout)和指向 std::list 的迭代器调用 operator <<。这是行不通的,因为迭代器类型没有这个运算符(为什么要有)。但是,迭代器是根据指针建模的,因此允许解除引用以访问它们所引用的元素。长话短说;这应该有效:

cout << *currentVertices;

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

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

所以,总结是

  1. currentVertices 是一个迭代器(或者你想说的指针),*currentVerticescontent of that iterator.
  2. 您需要 cout content of iterator 而不是 iterator

正如其他人已经提到的

 cout << currentVertices;

尝试打印迭代器。但是 operator<< 没有采用这种类型的第二个参数的重载。取消引用迭代器

 //      V
 cout << *currentVertices;

或者简化整个循环:

for(const auto &currentVertices : currentFace->setofVertices){
    cout << currentVertices;
}

您已经得到告诉您取消引用迭代器的答案:

for(auto currentVertices = currentFace->setofVertices.begin();
    currentVertices != currentFace->setofVertices.end();
    currentVertices++)
{
    cout << *currentVertices;   // dereference
}

但是,您可以使用基于范围的 for 循环自动执行此操作:

for(auto& currentVertices : currentFace->setofVertices) {
    cout << currentVertices;    // already dereferenced
}