2

I have a problem, using STL algorithm with QList: while executing it crashes. Debuger takes one more step into lambda, so before to crash entry is . (So, if list is empty is crashes at 1 iteration, if list has 1 element - at 2 iteration etc.).

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?

3
  • 1
    You probably want to use std::back_inserter(searchResult) as your output iterator Commented Jun 4, 2017 at 18:52
  • getStudentEntryList() doesn't return a copy, does it? Commented Jun 4, 2017 at 18:58
  • Your problem is not really Qt-related. It'll crash just the same with std::list. Have you looked at correct examples demonstrating the use of copy_if? Commented Jun 5, 2017 at 5:46

1 Answer 1

5

std::copy_if increments the output iterator when copying elements. You passed it searchResult.begin() which is equally an end() iterator since searchResult is an empty container. And increment(ing) an iterator passed the end() iterator invokes 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

std::copy_if(model->getStudentEntryList().begin(),
             model->getStudentEntryList().end(),
             std::back_inserter(searchResult),
             condition);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.