C++ 删除并查找的stl错误,如果
我使用vector student来表示多态性,因为我从基类学生中派生了本地学生和国际学生。现在的问题是我的函子有错误。我有两种删除方法。两者都不起作用。我该如何解决这个问题?哪种删除方法更好C++ 删除并查找的stl错误,如果,c++,vector,stl,C++,Vector,Stl,我使用vector student来表示多态性,因为我从基类学生中派生了本地学生和国际学生。现在的问题是我的函子有错误。我有两种删除方法。两者都不起作用。我该如何解决这个问题?哪种删除方法更好 void deleteStudent(vector <clsStudent*>& student) { cout << "Enter student name to delete"; student.erase(remove(student.begin(),
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_;
};
错误
错误:从“uuu gnu_cxx::uu normal_iterator”转换为非标量类型“std::vector::iterator{aka uuu gnu cxx::uu normal_iterator}”请求find_if的问题是s是对向量的常量引用,但返回的迭代器是非常量的,因此尝试更改为:
vector<clsStudent*>::const_iterator it = std::find_if(...)
您尚未发布要删除的调用的错误,但我怀疑这是因为您确实打算写:
remove_if(student.begin(), student.end(), MatchName(nameToDelete))
您报告的错误来自searchStudent方法
你的向量是常量,所以你不能使用迭代器,而是使用常量迭代器你真的应该发布MatchName。为什么要在main中包含io代码,而不是在发生错误的行上使用MatchName的签名?为什么不包括一份实际错误的副本?我将您的问题编辑为在代码中使用`字符,这样字符就不会被视为HTML,请在发布问题之前使用预览,以确保其格式正确,并请多花几秒钟写出正确的英语,“我不是im。对不起,忘了火柴的名字了。”乔纳森·韦克利,谢谢。下次我会记住这一点。
remove_if(student.begin(), student.end(), MatchName(nameToDelete))