【发布时间】:2012-01-21 05:55:19
【问题描述】:
我的 remove_if 似乎正在用过滤掉的元素的值覆盖未过滤掉的元素。这些代码的目的是允许用户过滤和仅显示某个类别的教师。 (不删除任何元素) 以下是部分代码
static string compare;
static string debug;
bool filter_Cat (Teacher &t)
{
return (t.getCat() != compare);
}
void filterCat (vector<Teacher> &t)
{
vector<Teacher>::iterator i;
vector<Teacher>::iterator newedited = remove_if(t.begin(), t.end(), filter_Cat);
for (i = t.begin(); i != newedited; ++i)
{
Teacher& te = *i;
te.getName();
cout << "\t";
te.getCategory();
cout << "\t";
te.getLocation();
}
}
void filterTutorCat(vector<Teacher> &t)
{
int choice;
cout << "No\tCategory" << endl
<< "1\tEnglish" << endl
<< "2\tMath" << endl
<< "3\tScience" << endl
<< "Choose the category you wish to filter :";
cin >> choice;
getline(cin, debug);
if(choice <= 3 && choice > 0)
{
if (choice == 1)
{
compare = "English";
filterCat(t);
}
if (choice == 2)
{
compare = "Math";
filterCat(t);
}
if (choice == 3)
{
compare = "Science";
filterCat(t);
}
}
else
{
cout << "Invalid Option" << endl;
}
}
【问题讨论】:
-
输入、预期输出和实际输出是什么?
-
从代码中可以看出,用户只能输入 1,2, 或 3 他们希望过滤的类别。对于预期的输出,它应该只显示用户选择的类别中的教师。如果只有一个类别与“比较”匹配的对象,则实际输出正确,但如果有 2 个类别与“比较”匹配的对象,则开始覆盖向量中的对象