【问题标题】:Vector insert crashes program矢量插入崩溃程序
【发布时间】:2010-10-01 03:26:46
【问题描述】:

谁能告诉我

为什么这会使我的程序崩溃?假设这样 order 使 t 向量中的所有元素位于 (y + height) 处。

编辑:在带有“插入”的行上崩溃。

void createDrawOrder(vector<Thing*> t, vector<int> *order) {
        int min = t[0]->y + t[0]->height;
        int max = t[0]->y + t[0]->height;

        vector<int>::iterator it;

        it = order->begin();

        order->push_back(0);

        for (int i = 1; i < (int) t.size(); i++) {
            if ((t[i]->y  + t[i]->height) < min) {
                min = (t[i]->y  + t[i]->height);
                order->insert(it, i);
            }

            else if((t[i]->y + t[i]->height) >= min && (t[i]->y + t[i]->height) < max){

                int tempsize = (int) order->size();

                for (int j = 0; j < tempsize; j++){
                    if((t[i]->y + t[i]->height) <= (t[(*order)[j]]->y + t[(*order)[j]]->height)){
                            order->insert(it + j, i);
                    }
                }
            }

            else if ((t[i]->y + t[i]->height) >= max) {
                max = (t[i]->y + t[i]->height);
                order->push_back(i);
            }
        }

    }//end method max

【问题讨论】:

    标签: c++ vector crash sdl


    【解决方案1】:

    您的迭代器 it 不能保证在 order-&gt;push_back(k); 之后有效,它可以重新分配向量中的元素。由于我没有看到您在任何地方实际增加 it,我建议在此函数中用 order-&gt;begin() 替换它的更丑陋的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多