3

Consider the following code:

#include <string>
#include <list>

using namespace std;

int main(int argc, const char * argv[])
{
    list<int> l{1,2,3,4};
    list<list<int>> ll;
    ll.push_back(l);
    return 0;
}

After the push_back, the ll list is containing one empty element. I am wondering why it is not filled with the content of list l.

Note: I am on Mac OS 10.9 using Xcode 5.0.1.

Edit 1:

Here is the lldb output:

(lldb) p l
(std::__1::list<int, std::__1::allocator<int> >) $0 = size=4 {
  [0] = 1
  [1] = 2
  [2] = 3
  [3] = 4
}
(lldb) p ll
(std::__1::list<std::__1::list<int, std::__1::allocator<int> >, std::__1::allocator<std::__1::list<int, std::__1::allocator<int> > > >) $1 = size=1 {
  [0] = size=0 {}
}
(lldb) 

Edit 2

As @molbdnilo said, it looks like a debugger issue because when a new list initialized with the first item of ll I get the same content than in l.

Kevin MOLCARD
  • 2,168
  • 3
  • 22
  • 35

2 Answers2

1

Hope this sample code helps to manipulate in list stl,

#include <iostream>

#include <string>
#include <list>

using namespace std;

int main(int argc, const char * argv[])
{
   list<int> l{1,2,3,4};
   list<int> l1{5,6,7,8};
   list<list<int>> ll;
   ll.push_back(l);
   ll.push_back(l1);
   list<list<int>>::iterator itr;
   for (itr=ll.begin(); itr != ll.end(); itr++)
   {
       list<int>tl=*itr;
       list<int>::iterator it;
       for (it=tl.begin(); it != tl.end(); it++)
       {
           cout<<*it;
       }
       cout<<endl<<"End"<<endl;
   }
   return 0;

}

Saravanan
  • 1,270
  • 1
  • 8
  • 15
0

Your code actually will fill ll with the contents of list l. So if you continue it as follows:

#include <string>
#include <list>
#include <algorithm>
#include <iostream>

int main(int argc, const char * argv[])
{
    std::list<int> l{1,2,3,4};
    std::list<std::list<int>> ll;
    ll.push_back(l);
    auto first_list = *(ll.begin());
    auto second_element_of_first_list = *(std::next(first_list.begin()));
    std::cout << second_element_of_first_list << "\n";
    return 0;
}

This will print 2. See it running on cpp.sh.

einpoklum
  • 118,144
  • 57
  • 340
  • 684