如何正确从向量中删除具有与用户定义匹配的变量的对象?

问题描述 投票:0回答:1

如果对象的用户定义 ID(存储在变量中)与用户想要从向量中删除的 ID 匹配,我将尝试从向量中正确删除对象。

代码在这里:

class Employee {
public:
    std::string empID, empName, empTitle, empHireDate, empSalary;
    Employee() {}
    // constructor
    Employee(string id, string name, string title, string hireDate, string salary) :
        empID(id),
        empName(name),
        empTitle(title),
        empHireDate(hireDate),
        empSalary(salary)
        {}

        //note, this is unneeded, ignore it.
        //returns the employee's ID
    string getEmpID() {
        return empID;
    }
}

此代码将位于 main 中,忽略 else-if 输入语句,该语句用于选项菜单。

//command to delete an employee from the system
else if (input == "4") {
    cout << "Insert employee ID you wish to delete: ";
    cin >> input;
    //finds the employee, and deletes them from the vector
    for (Employee employees : Payroll) {
    if (input == employees.getEmpID()) {
        Payroll.erase(std::remove(Payroll.begin(), Payroll.end(), employees));
    }
}

如前所述,如果用户在向量中具有正确的 ID 和“员工”,我想从向量中删除该员工。

但是,当我运行代码时,编译器会输出源自“Payroll.erase(std::remove(Payroll.begin(), Payroll.end(),Employees));”的 C2676 错误。行,更具体地说是“删除”命令。

c++ std
1个回答
0
投票

您的代码存在一些问题:

  • Employee
    不实现
    operator==
    std::remove()
    用于比较
    Employee
    实例。这就是编译器错误的原因。

  • 您正在更改

    std::vector
    ,同时使用
    range-for
    循环进行迭代。
    vector::erase()
    调用将使循环内部使用的迭代器无效,从而导致未定义的行为。

您根本不需要

for
循环。您可以使用
std::remove_if()
代替:

Payroll.erase(
    std::remove_if(
        Payroll.begin(), Payroll.end(),
        [&](Employee &e){ return input == e.getEmpID(); }
    ),
    Payroll.end()
);

或者,在 C++20 及更高版本中,您可以使用

std::erase_if()
代替,例如:

std::erase_if(Payroll,
    [&](Employee &e){ return input == e.getEmpID(); }
);

无论哪种方式都会扫描整个

vector
删除所有匹配的
Employee
对象,就像您的原始代码试图做的那样。

但是,如果只有 1 个具有匹配 ID 的

Employee
对象,那么在找到匹配项后继续扫描就没有意义了。您应该使用
std::find_if()
代替,例如:

auto iter = std::find_if(
    Payroll.begin(), Payroll.end(),
    [&](Employee &e){ return input == e.getEmpID(); }
);
if (iter != Payroll.end())
    Payroll.erase(iter);
© www.soinside.com 2019 - 2024. All rights reserved.