visual c++ - C++ question regarding inserting elements into vectors -
i working through examples in accelerated c++. 1 of problems asks reader copy records students pass exams beginning of vector called students. fgrade
function defined elsewhere returns failing students. 1 has use resize function remove elements students contains pass. have tried code not work. tell me if fault lies in code below?
#include "stdafx.h" #include <vector> #include "student_info.h" #include "grade.h" using std::vector; // second try: correct potentially slow vector<student_info> extract_fails(vector<student_info>& students) { vector<student_info> fail; #ifdef _msc_ver std::vector<student_info>::size_type = 0; std::vector<student_info>::size_type count = 0; #else vector<student_info>::size_type = 0; vector<student_info>::size_type count = 0; #endif while (i != students.size()) { if (!fgrade(students[i])) { students.insert(students.begin(), students[i++]); count++; } i++; } students.resize(count); return students; }
you increment i
twice in loop.
a cool way use custom predicate std::sort
:
bool comparestudentsbyfailure(const student_info & left, const student_info & right) { return fgrade(left) > fgrade(right); }
and use this:
std::sort(students.begin(), students.end(), comparestudentsbyfailure); students.resize(std::distance(students.begin(), std::find_if(students.rbegin(), students.rend(), fpgrade).base()));
however, jon`s answer bit simpler.
Comments
Post a Comment