|
-
May 31st, 2012, 08:59 PM
#1
push_back on a vector crashing
Hi Guys,
Could someone please help me figure out what I am trying to do here. I have a function that takes a vector of structures(in this example single structure is a student record) and returns that same vector after doing some re-arrangements to it. So I have a while loop to go through the vector and check each element to see if the student passed or failed the class. If it passed, I want to add that element back to the existing vector (push_back into it). If it failed, I don't want to do anything. At the end, I want to resize the vector to only how many students passed, since every time I push_back passed student into the vector, I increment int p and that way I will know how much to cut at the end. Here is the code:
Code:
vector<Student_info> extract_fails(vector<Student_info>& students){
vector<Student_info>::iterator it = students.begin();
int p = 0;
while(it != students.end())
{
if (!fgrade(*it)) { // if student didn't fail
p++;
students.push_back(*it); // add to the beginning of the vector
}
else
{
++it; // do nothing, go to next record
}
}
students.resize(p); // cut the vector to contain only the first p elements (so I return the vector of only those students who passed the class)
return students;
}
The problem is that my program totally crashes somewhere along these lines and stops working. I am suspecting that after push_back operations, my iterators on the vector are invalidated and I really have no idea where it starts next in the while loop.
Any thoughts?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|