简体   繁体   中英

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".

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 << " "; 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.

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 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 . Its declaration should look like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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