开发者

Vector insert crashes program

开发者 https://www.devze.com 2023-01-18 03:08 出处:网络
Can anyone tell me why this crashes my program? It\'s suppose to make it so order has all the elements in the t vector situated by (y + height).

Can anyone tell me

why this crashes my program? It's suppose to make it so order has all the elements in the t vector situated by (y + height).

Edit: crashes on the lines with 开发者_如何学C"insert" in them.

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


Your iterator it is not guaranteed to be valid after order->push_back(k); which can reallocate the elements in your vector. Since I don't see you actually incrementing it anywhere, I'd recommend the uglier solution of replacing it with order->begin() in this function.

0

精彩评论

暂无评论...
验证码 换一张
取 消