【发布时间】:2021-01-11 18:20:52
【问题描述】:
我想删除给定卷号的特定学生对象。从学生列表中使用 STL 中的擦除操作。以下是我的班级设计。 但是编译器在我使用擦除功能的地方显示以下错误消息。
没有重载函数“std::vector<_tp _alloc>::erase [with _Tp=Student, _Alloc=std::allocator
]”的实例与参数列表匹配——参数类型为:(Student ) -- 对象类型为: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";
}
};
【问题讨论】:
-
旁注:存储迭代器 (
vector <Student>::iterator it;) 存在一定风险,因为它很容易通过在vector中添加或删除项目而变得无效。请参阅Iterator invalidation rules,了解标准修订版的逐个标准修订细分,了解您可以和不可以逃避的事情。