我想要删除一个特定的学生对象,为一个给定的卷否。在STL中使用擦除操作从学生列表中删除。以下是我的课堂设计。但是编译器在我使用擦除函数的地方显示了下面的错误消息。
没有重载函数"std::vector<_Tp,_Alloc>::erase with _Tp=Student,_Alloc=std::allocator“的实例与参数列表匹配--参数类型是:(学生) --对象类型是: std::vector
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
class Student
{
int roll;
char *name;
int score;
public:
Student(int r=0)
{
roll=r;
}
void get_data()
{
cout<<"Enter roll : ";
cin>>roll;
cout<<"Enter name : ";
cin>>name;
cout<<"Score : ";
cin>>score;
}
void show_data()
{
cout<<"Roll : "<<roll<<endl;
cout<<"Name : "<<name<<endl;
cout<<"Score : "<<score<<endl;
}
int ret_score()
{
return score;
}
int ret_roll()
{
return roll;
}
};
class Student_array
{
public:
vector <Student> Student_array;
vector <Student>::iterator it;
void add_student()
{
Student s;
s.get_data();
Student_array.push_back(s);
}
void remove_student()
{
int roll;
cout<<"Enter roll no. of the student to be removed : ";
cin>>roll;
for(int i=0;i<Student_array.size();i++)
{
if(roll==Student_array[i].ret_roll())
{
Student_array.erase(Student_array[i]);
break;
}
}
cout<<"Roll no. not found enter a valid roll no.\n";
}
};发布于 2021-01-11 18:26:48
std::vector::erase()将迭代器作为输入,而不是Student对象,例如:
void remove_student()
{
int roll;
cout << "Enter roll no. of the student to be removed : ";
cin >> roll;
for(int i = 0; i < Student_array.size(); ++i)
{
if (roll == Student_array[i].ret_roll())
{
Student_array.erase(Student_array.begin() + i);
return; // <-- not 'break'!
}
}
cout << "Roll no. not found enter a valid roll no.\n";
}或者,您可以使用std::find_if()来查找所需的Student,而不是使用手动循环,例如:
void remove_student()
{
int roll;
cout << "Enter roll no. of the student to be removed : ";
cin >> roll;
auto iter = std::find_if(Student_array.begin(), Student_array.end(),
[=](Student &s){ return s.ret_roll() == roll; }
);
if (iter != Student_array.end())
Student_array.erase(iter);
else
cout << "Roll no. not found enter a valid roll no.\n";
}发布于 2021-01-11 18:28:21
必须使用迭代器擦除元素。
for (auto iter = Student_array.begin(); iter != Student_array.end(); ++iter)
{
if (roll != iter->ret_roll())
continue;
Student_array.erase(iter);
break;
}https://stackoverflow.com/questions/65672471
复制相似问题