【问题标题】:How to correctly fill a list of list in c++如何在 C++ 中正确填写列表列表
【发布时间】:2013-12-18 11:49:29
【问题描述】:

考虑以下代码:

#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的内容。

注意:我在 Mac OS 10.9 上使用 Xcode 5.0.1。

编辑 1:

这里是 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) 

编辑 2

正如@molbdnilo 所说,这看起来像是一个调试器问题,因为当使用ll 的第一项初始化新列表时,我得到的内容与l 中的内容相同。

【问题讨论】:

  • 在 VC++12 上为我工作。你是如何测试的?也许您正在发布模式下进行调试?
  • 你怎么知道它是空的? ll 在我的系统上包含 1 个四元素列表 (g++ 4.8)
  • 向我们展示你如何找到ll的内容的代码?
  • Don't simply wonder 显示一些代码来证明你的观点
  • 看起来像调试器显示问题;我得到了同样的效果,但是如果我将 *ll.begin() 分配给一个新列表,那么该列表就是它应该的样子。所以很可能是苹果的错误。

标签: c++ list stl std


【解决方案1】:

希望此示例代码有助于在列表 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;

}

【讨论】:

    【解决方案2】:

    您的代码实际上将使用列表l 的内容填充ll。所以如果你继续如下:

    #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 上运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多