简体   繁体   中英

Vector iterator not incremental

I'm trying to implement a simple menu application in Qt and I got to the point where I have to make a filter button. Qt is giving an error and I don't know how to interpret it. It could come only from these 2 functions. I'll post a photo of the error as well. Code for the filter operation:

vector<Car> Controller::filterByCategory(string category) {
    vector<Car> fin;
    vector<Car> all(repo->getAll());

    copy_if(all.begin(), all.end(),fin.begin(),
                [&](Car& cc) { return (cc.getCategory()==category); });
    return fin;
}

Qt function calling the filter function:

void OwnerWindow::filterCategory() {
    QString sCategory = lCategory->text();
    string category = sCategory.toStdString();
    vector<Car> cars = ctrl->getAllCars();
    vector<Car> fin;
    try {
        fin = ctrl->filterByCategory(category);
    }
    catch(WarehouseException& ex) {
            QMessageBox::information(this, "Error!", QString::fromStdString(ex.getMsg()));
    }
    catch(...) {
        QMessageBox::information(this,"wtf",QString::fromStdString("huuuuuh"));
    }

Here my program crashes with the following error: 在此处输入图片说明

Any idea what could be happening, why Qt won't catch some error or why the code is not working?

EDIT: I tried to count the number of elements i will add so I can create my final vector with a fixed size. Didn't work.

vector<Car> Controller::filterByCategory(string category) {
//    vector<Car> fin;
    vector<Car> all(repo->getAll());
    int i = 0;
    for_each(all.begin(),all.end(), [=](const Car& cc) mutable {
        if (cc.getCategory() == category) {
            i++;
        }
    });
    vector<Car> fin(i);
    copy_if(all.begin(), all.end(),fin.begin(),
                [&](Car& cc) { return (cc.getCategory()==category); });
    return fin;
}

The problem with filterByCategory is that the vector fin is empty , you either need to create it with the correct number of elements, or use std::back_inserter to create elements on demand.

By the way, there's no need to copy into the all vector first. Use eg repo->getAll().begin() directly in the std::copy_if call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM