简体   繁体   English

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

[英]Using STL algorithms with Qt containers

I have a problem, using STL algorithm with QList: while executing it crashes. 我有一个问题,使用带有QList的STL算法:执行时崩溃。 Debuger takes one more step into lambda, so before to crash entry is . Debuger又向lambda迈出了一步,所以在崩溃之前就是。 (So, if list is empty is crashes at 1 iteration, if list has 1 element - at 2 iteration etc.). (因此,如果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);
}

How can I solve the problem? 我该如何解决这个问题?

std::copy_if increments the output iterator when copying elements. 复制元素时, std::copy_if增加输出迭代器。 You passed it searchResult.begin() which is equally an end() iterator since searchResult is an empty container. 你传递了它的searchResult.begin() ,它同样是一个end()迭代器,因为searchResult是一个空容器。 And increment(ing) an iterator passed the end() iterator invokes Undefined Behavior. 并且递增(通过)传递end()迭代器的迭代器会调用Undefined Behavior。

since QList<T> supports a push_back(T) member function, you should use std::back_inserter to create a std::back_insert_iterator that will be doing push back's to searchResult 因为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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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