我正在使用vector<clsStudent*>
学生进行多态性,因为我从基础学生那里获得了本地学生和国际学生。现在的问题是我的仿函数有错误。我有两种删除方法。两者都不起作用。我该如何解决?哪种删除方法更好?
void deleteStudent(vector <clsStudent*>& student)
{
cout << "Enter student name to delete";
student.erase(remove(student.begin(), student.end(), nameToDelete), student.end());
vector <clsStudent*>::iterator it = student.begin();
while (it != student.end())
{
if (*it == nameToDelete)
{
it = student.erase(it);
}
else{
++it;
}
}
}
void searchStudent(const vector <clsStudent*>& s)
{
string searchName;
cout << "\nEnter student name to search for. Press [Q] to terminate." << endl;
cin >> searchName;
if (s.size() == 0)
cout << "There is 0 student in the database.";
while(searchName != "q")
{
vector<clsStudent*>::iterator it = std::find_if(s.begin(),
s.end(),
MatchName(searchName)); <---- ERROR here
}
int main()
{
char choice;
clsUniversityProgram objProgram[3];
for (int x = 0; x < 3; x++)
{
objProgram[x].programInfo();
}
vector <clsStudent*> student;
do
{
cout <<"\nPress [A] to add new student"
<< "\nPress [L] to list existing stundet"
<< "\nPress [M] to modify existing student"
<< "\nPress [O] to sort student data by name"
<< "\nPress [W] to write students data to file"
<< "\nPress [R] to read students data from file"
<< "\nPress [D] to delete a student"
<< "\nPress [X] to exit"
<< "\nEnter your choice: " << endl;
choice = toupper(getch());
switch(choice){
case 'A':
addStudents(student, objProgram);
break;
case 'L':
{
for(int x = 0; x < student.size(); x++)
{
student[x]->printStudentDetails();
student[x]->print();
}
break;
}
case 'M':
// modify
case 'O':
sortStudentbyName(student);
break;
case 'W':
// write
break;
case 'R':
// read
break;
case 'D':
deleteStudent(student);
break;
case 'X':
return 0;
default:
cerr << "Invalid input!" << endl;
break;
}
} while (choice != 'L'
&& choice != 'M'
&& choice != 'O'
&& choice != 'W'
&& choice != 'R'
&& choice != 'D');
return 0;
}
struct MatchName
{
MatchName(string& searchName) : s_(searchName) {}
bool operator()(const clsStudent* student) const
{
return student->getName() == s_;
}
private:
string s_;
};
错误
error: conversion from '__gnu_cxx::__normal_iterator<clsStudent* const*, std::vector<clsStudent*> >' to non-scalar type 'std::vector<clsStudent*>::iterator {aka __gnu_cxx::__normal_iterator<clsStudent**, std::vector<clsStudent*> >}' requested|
答案 0 :(得分:2)
find_if
的问题是s
是对向量的const引用,但是你返回的迭代器是非const的,所以尝试改为:
vector<clsStudent*>::const_iterator it = std::find_if(...)
或者,如果您使用的是C ++ 11编译器,那么您可以使用auto
为您推断出正确的const /非const迭代器:
auto it=std::find_if(...)
您尚未发布remove
来电的错误,但我怀疑是因为您真的打算写:
remove_if(student.begin(), student.end(), MatchName(nameToDelete))
答案 1 :(得分:1)
您报告的错误来自您的searchStudent方法。
你的向量是const,所以你不能使用迭代器,而是使用const_iterator