繁体   English   中英

错误:'operator&lt;&lt;' 不匹配(操作数类型是 'std::ostream' {aka 'std::basic_ostream<char> '} 和 'std::_List_iterator<int> ')</int></char>

[英]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 list 本身?),但是

cout << currentVertices;

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

cout << *currentVertices;

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

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

所以,总结是

  1. currentVertices是一个迭代器(或指针,如果你想说的话), *currentVertices是该content 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM