我正在通过Accelerated C++中的示例工作。 其中一个问题是要求读者将通过考试的学生的记录复制到名为学生的媒介的开头。 fgrade
是其他地方定义的函数,返回失败的学生。 然后人们必须使用resize函数从学生中删除额外的元素,所以它只包含那些通过。 我试过这段代码,但它不起作用。任何人都可以告诉我,如果错误在于下面的代码?关于将元素插入向量的C++问题
#include "stdafx.h"
#include <vector>
#include "Student_info.h"
#include "grade.h"
using std::vector;
// second try: correct but potentially slow
vector<Student_info> extract_fails(vector<Student_info>& students)
{
vector<Student_info> fail;
#ifdef _MSC_VER
std::vector<Student_info>::size_type i = 0;
std::vector<Student_info>::size_type count = 0;
#else
vector<Student_info>::size_type i = 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;
}
你的循环中你有两次i ++,因此你的代码将跳过所有奇怪的学生。如果students.size()不是偶数,循环将永远存在。 – Artium 2011-01-26 10:24:50
在这种状态下,您将一名学生带入向量中,并且如果条件匹配,则将_same_学生插入向量中。所以你有两次在向量中...也许你需要使用'失败'向量... – 2011-01-26 10:27:43
修改vector_as真的是一个好主意_as你迭代它_?特别是因为你使用索引来通过每个学生,复制通过的学生到矢量的开头,你依靠那里的重复`i ++`来保存你的熏肉。如果是我,我只会使用第二个向量。 – sarnold 2011-01-26 10:28:18