2011-01-26 21 views
0

我正在通过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; 
} 
+0

你的循环中你有两次i ++,因此你的代码将跳过所有奇怪的学生。如果students.size()不是偶数,循环将永远存在。 – Artium 2011-01-26 10:24:50

+0

在这种状态下,您将一名学生带入向量中,并且如果条件匹配,则将_same_学生插入向量中。所以你有两次在向量中...也许你需要使用'失败'向量... – 2011-01-26 10:27:43

+0

修改vector_as真的是一个好主意_as你迭代它_?特别是因为你使用索引来通过每个学生,复制通过的学生到矢量的开头,你依靠那里的重复`i ++`来保存你的熏肉。如果是我,我只会使用第二个向量。 – sarnold 2011-01-26 10:28:18

回答

0

您在循环中增加了两次i

一个很酷的方式做到这一点是使用自定义的谓词std::sort

bool CompareStudentsByFailure(const Student_info & left, 
           const Student_info & right) { 
    return fgrade(left) > fgrade(right); 
} 

,然后用它是这样的:

std::sort(students.begin(), students.end(), CompareStudentsByFailure); 
students.resize(std::distance(students.begin(), 
       std::find_if(students.rbegin(), 
          students.rend(), fpgrade).base())); 

然而,Jon`s answer有点简单。

0

As Space_C0wb0y和Artium指出,你增加了两倍。此外,你声明矢量失败,但从来没有使用它(除非你以后用它做什么)。另外,函数中的宏看起来像是矫枉过正 - 它基本上说了同样的事情两次(减去“std ::”),你可能只是使用整数 - 更容易让下一个人阅读和理解。

1

您可以从标准::算法的remove_if使用,但仿函数应该返回那些未通过人(f_not_grade),而不是具有人传:

std::remove_if(students.begin(), students.end(), f_not_grade) 

或者你可以看的方式否定函子herehere以使用不带修改的f_grade函数和remove_if。

容器的大多数常见操作都是在STL中实现的,所以请使用语言的力量!花一些时间寻找这种功能使我们编码更少,更好。

编辑删除不正确的“()”。