Gytautė
Gytautė

Reputation: 33

How to fix error "vector iterators in range are from different containers" in c++?

I don't know where is the problem. The program crashes in this function. Can you help me?

I use these 2 functions for benchmarking (comparing containers speed with different techniques of using it). I use vector "studentai" with all students name and lastname in it. At vector "silpni" are students, which final score is >5. And, of course, "geri" with score <5. This function work well:

void atrinkimas_1(vector <duomenys>& studentai, vector <duomenys>& silpni, vector <duomenys>& geri)
{
    sort(studentai.begin(), studentai.end(), tikrinimas_gal);
    std::vector<duomenys>::iterator it = std::find_if(studentai.begin(), 
    studentai.end(), tikrinimas_5);
    std::copy(it, studentai.end(), std::back_inserter(geri));
    studentai.resize(studentai.size() - geri.size());
    std: copy(studentai.begin(), it, std::back_inserter(silpni));
    studentai.clear();
}

And this doesn't:

void atrinkimas_2(vector <duomenys>& studentai, vector<duomenys> &silpni)
{
    sort(studentai.begin(), studentai.end(), tikrinimas_gal);
    std::vector<duomenys>::iterator it = std::find_if(studentai.begin(), studentai.end(), tikrinimas_5);
    std::copy(it, studentai.end(), std::back_inserter(silpni));
    studentai.resize(studentai.size() - silpni.size());
}

What is the problem?

Upvotes: 1

Views: 3916

Answers (1)

Ben
Ben

Reputation: 9703

By resizing studentai, you’ve invalidated it. I would guess that the error is that it doesn’t point into studentai anymore.

Upvotes: 2

Related Questions