简体   繁体   English

打印列表列表 C++ STL 列表

[英]Printing a list of lists C++ STL list

I have a top list that stores inner lists.我有一个存储内部列表的顶级列表。 I'm using the standard template library list template.我正在使用标准模板库列表模板。

I am attempting to print the values of the inner lists.我正在尝试打印内部列表的值。 The top list is "L" and the inner list is "I".顶部列表是“L”,内部列表是“I”。

void ListofLists::dump()
{
    list<list<IntObj>>::iterator itr;
    for (itr = L.begin(); itr != L.end(); itr++)
    {
        list<IntObj>::iterator it;
        for (it = I.begin(); it != I.end(); it++)
        {
            cout << *it << "  ";
        } 
        cout << endl << "End" << endl;
    }
}

My IDE doesn't like the line cout << *it << " ";我的 IDE 不喜欢cout << *it << " "; and I'm not really sure how to change it while having the program do what I want it to do, which is print the data inside of the lists.并且我不确定如何在让程序执行我想要它做的事情时更改它,即在列表中打印数据。 It red underlined the “<<“ operator and says “no operator “<<“ matches these operands.”它在“<<”运算符下划线并表示“没有运算符“<<”与这些操作数匹配。”

Can someone help me as to why?有人可以帮助我为什么吗? I've looked and can't really find what I'm looking for.我已经看过了,但真的找不到我要找的东西。 I'm not understanding something correctly.我没有正确理解某些东西。 I know it is adding the data to the data structure correctly because my IDE enables me to view my locals.我知道它正确地将数据添加到数据结构中,因为我的 IDE 使我能够查看我的本地人。

Thanks to anyone who helps!感谢任何帮助的人! Means a lot.意义重大。

Try to use :尝试使用:

list<IntObj>::const_iterator i;

instead the one you are using to avoid compiling error.而不是您用来避免编译错误的那个。

The inner loop does not make sense.内循环没有意义。

If you want to use iterators then the function can be defined like如果你想使用迭代器,那么函数可以像这样定义

void ListofLists::dump() /* const */
{
    for (list<list<IntObj>>::iterator itr = L.begin(); itr != L.end(); itr++)
    {
        for ( list<IntObj>::iterator it = itr->begin(); it != itr->end(); it++)
        {
            cout << *it << "  ";
        } 
        cout << endl << "End" << endl;
    }
}

However it will be simpler to use the range-based for loop.然而,使用基于范围的 for 循环会更简单。 For example例如

void ListofLists::dump() /* const */
{
    for ( const auto &inner_list : L )
    {
        for ( const auto &item : inner_list )
        {
            cout << item << "  ";
        } 
        cout << endl << "End" << endl;
    }
}

Take into account that you have to define the operator << for the class IntObj .考虑到您必须为类IntObj定义operator << Its declaration should look like它的声明应该看起来像

std::ostream & operator <<( std::ostream &, const IntObj & );

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

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