0

I have two lists

list<int> s;
list<std::list<int>> q;

and I did the following assignment

q.push_front(s);

How can I display the contents of q since this

for (q_iterator = q.begin(); q_iterator != q.end(); ++q_iterator)
    for (s_iterator = q_iterator.begin(); s_iterator != q_iterator.end(); ++s_iterator)
        cout << *s_iterator;

gives me an error?

  • 1
    `q_iterator->begin();` a.s.o. – πάντα ῥεῖ May 16 '15 at 11:26
  • 1
    The error here may be obvious to experienced developers but in general this question is not up to standards because it does not contain enough information (the error message!). As an aside, note that you can generalize this type of access with a [flattening iterator](http://stackoverflow.com/q/3623082/50079) – Jon May 16 '15 at 11:28

2 Answers2

4

You have to write the following way

for (q_iterator = q.begin(); q_iterator != q.end(); ++q_iterator)
    for (s_iterator = q_iterator->begin(); s_iterator != q_iterator->end(); ++s_iterator)
        cout << *s_iterator;

or the following way

for (q_iterator = q.begin(); q_iterator != q.end(); ++q_iterator)
    for (s_iterator = ( *q_iterator ).begin(); s_iterator != ( *q_iterator ).end(); ++s_iterator)
        cout << *s_iterator;

provided that q_iterator and s_iterator are already declared. Otherwise you could write for example

for ( auto q_iterator = q.begin; /*...*/ )

Also you can use the range based for statement. For example

for ( const auto &s : q )
{
    for ( int x : s ) std::cout << x << ' ';
    std::cout << std::endl;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

You probably know it, but I just want to make sure you remember about a space between angle braces.

std::list<std::list<int> >
Kamil Kuczaj
  • 193
  • 1
  • 8