请考虑以下代码:
#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;
}
在push_back
之后,ll
列表包含一个空元素。
我想知道为什么它没有填充列表l
的内容。
注意:我使用Xcode 5.0.1在Mac OS 10.9上。
这是lldb输出:
(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)
正如@molbdnilo所说,它看起来像是一个调试器问题,因为当使用ll
的第一项初始化新列表时,我得到的内容与l
中的内容相同。
答案 0 :(得分:2)
希望此示例代码有助于在列表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;
}
答案 1 :(得分:0)
您的代码实际上将用列表ll
的内容填充l
。因此,如果您继续执行以下操作:
#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;
}
这将打印2
。看到它在cpp.sh上运行。