簡體   English   中英

將STL算法與Qt容器一起使用

[英]Using STL algorithms with Qt containers

我有一個問題,使用帶有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);
}

我該如何解決這個問題?

復制元素時, 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM