Hi everyone.
This regards exercise 5-6 of "Accelerated C++".
I am asked to rewrite a function so that instead of using erase() to remove an element (of a failing student), I should copy the elements (of the passing students) to the beginning of the vector and then use resize() to remove the unnecessary elements from the end of the vector.
The program compiles but crashes once it gets to this point. It ran fine using erase().
My code for this function is as follows, where container_Student_info is a typedef for vector<Student_info>:
Ignore std::list. It is there as part of another exercise I'm working on and also failing at ;P.
#include "fail.h"
#include "grade.h"
using std::vector; using std::list;
container_Student_info extract_fails(container_Student_info& students)
{
container_Student_info::size_type p = 0; // code for copy and resize
container_Student_info fail;
container_Student_info::iterator iter = students.begin();
container_Student_info::iterator it = students.begin(); // code for copy and resize
while(iter!=students.end())
{
if(fgrade(*iter))
{
fail.push_back(*iter);
++iter; // code for copy and resize
//iter = students.erase(iter);
}
else
{
it = students.begin(); // code for copy and resize
students.insert(it, *iter); // code for copy and resize
++p; // code for copy and resize
++iter;
}
}
students.resize(p); // code for copy and resize
return fail;
}
bool fgrade(const Student_info& s)
{
return grade(s) < 60;
}
So my question is, why is it crashing? Cheers.