[英]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中实现一个简单的菜单应用程序,而我不得不做一个过滤器按钮。 Qt is giving an error and I don't know how to interpret it.
Qt给出了一个错误,我不知道如何解释它。 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: Qt函数调用filter函数:
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? 知道可能会发生什么,为什么Qt不会捕获某些错误,或者为什么代码不起作用?
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. filterByCategory
的问题在于向量fin
为空 ,您要么需要使用正确数量的元素创建它,要么使用std::back_inserter
来按需创建元素。
By the way, there's no need to copy into the all
vector first. 顺便说一句,不需要先复制到
all
向量中。 Use eg repo->getAll().begin()
directly in the std::copy_if
call. 直接在
std::copy_if
调用中使用例如repo->getAll().begin()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.