将STL算法与Qt容器一起使用

Мар*_*вич 2 c++ algorithm qt stl c++11

我有一个问题,使用带有QList的STL算法:执行时崩溃.Debuger又向lambda迈出了一步,所以在崩溃之前就是.(因此,如果list为空则在1次迭代时崩溃,如果list有1个元素 - 在2次迭代时等).

void FindDialog::findEntries()
{
    QList<StudentEntry> searchResult;

    condition = [this] (const StudentEntry &entry) -> bool {
                // crashes here 
                return entry.name.getSurname() == surnameEdt1->text() &&
                       entry.group.getValue() == groupEdt->text();
                };

    std::copy_if(model->getStudentEntryList().begin(),
                 model->getStudentEntryList().end(),
                 searchResult.begin(),
                 condition);
}
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Whi*_*TiM 5

std::copy_if复制元素时递增输出迭代器.你传递了它searchResult.begin()同样是一个end()迭代器,因为它searchResult是一个空容器.并且递增(通过)迭代器传递end()迭代器会调用Undefined Behavior.

因为QList<T>支持一个push_back(T)成员函数,你应该使用std::back_inserter创建一个std::back_insert_iterator将要回推的成员函数searchResult

std::copy_if(model->getStudentEntryList().begin(),
             model->getStudentEntryList().end(),
             std::back_inserter(searchResult),
             condition);
Run Code Online (Sandbox Code Playgroud)