使用擦除删除 class 对象数组中的元素

Using erase for removing an element in an array of class objects

我想删除给定卷号的特定学生对象。从学生列表中使用 STL 中的擦除操作。以下是我的 class 设计。 但是编译器在我使用擦除函数的地方显示了以下错误信息。

no instance of overloaded function "std::vector<_Tp, _Alloc>::erase [with _Tp=Student, _Alloc=std::allocator<Student>]" matches the argument list -- argument types are: (Student) -- object type is: std::vector<Student, std::allocator<Student>>

#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";
    }
};

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";
}

你必须使用迭代器来擦除一个元素

for (auto iter = Student_array.begin(); iter != Student_array.end(); ++iter)
{
    if (roll != iter->ret_roll())
        continue;

    Student_array.erase(iter);
    break;
}