【问题标题】:Impossible to make a <list <list< int* > > work不可能使 <list <list< int* > > 工作
【发布时间】:2016-02-02 06:03:10
【问题描述】:

尽管我花费了不合理的时间,但我有一个无法解决的问题。我想要一个列表 >,但它不起作用。这是我的代码:

int main(int argc, const char * argv[]) {
   int a=2;
   int b=3;

   list<list<int*>> test;

   list< list<int*> >::iterator it;
   it = test.begin();

   it->push_back(&a);
   it->push_back(&b);

   b=4; //should modify the content of "test"

   for(list <int*>::iterator it2 = it->begin(); it2 != it->end(); it2++) {
      cout << *it2 << endl;
   }
}

使用 xCode 可以编译,但出现“线程 1:EXC_BAD_ACCESS”错误。希望大家多多指教!

谢谢!

【问题讨论】:

    标签: c++ list pointers stl


    【解决方案1】:

    test 为空,因此test.begin() 是一个单数迭代器,取消引用它是非法的。它会导致未定义的行为,类似于越界访问数组。

    你需要这样做:

    test.emplace_back();
    it = test.begin();
    

    这将向test 添加一个新的值初始化元素,因此它将成为一个包含零元素列表的单元素列表。然后it 将指向该单个元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      相关资源
      最近更新 更多