首页 > 解决方案 > 如何使用 for 循环删除 C++ 中的特定索引项

问题描述

我目前的 lastIndex 等于-1。我的目标是循环遍历一组学生和值,使用“按 id 删除”函数,删除该 id 和一组值,并将其替换为下一个值,这样中间就没有空行。经过测试,我发现最后一个索引引用了实际的最后一个索引,但我需要它来引用我要删除的第三个 id。如果我删除“名册::lastIndex--;” 它删除了第 5 个(最后一个)索引,并在第 3 行中给出了应该删除的以下值。这里的编辑不会让我发帖,但它是一组带有 ? 里面

void Roster::removeStudentById(string studentId) {
    bool success = false;
    for(int i = 0; i <= Roster::lastIndex; i++)
    {
        if (studentRosterArray[i]->getStudentID() == studentId)
        {
            success = true;
            if (i < numRoster - 1)
            {
                Student *temp = studentRosterArray[i];
                studentRosterArray[i] = studentRosterArray[numRoster - 1];
                studentRosterArray[numRoster - 1] = temp;
            }
            Roster::lastIndex--;
        }
    }
    if (success)
    {
        cout << studentId << " removed from roster." << std::endl << std::endl;

    }
    else cout << studentId << " not found." << std::endl << std::endl;
}

标签: c++pointers

解决方案


如果您的解决方案需要删除一些项目,请尝试使用std::listor std::unordered_maporstd::map基于数据性质,以获得更好的性能!

对于您的代码,您可以std::unordered_map用作

std::unordered_map<std::string, Student> students;

void Roster::removeStudentById(std::string studentId)
{
    auto iter = students.find(studentId);
    if (iter == students.end())
    {
        std::cout << studentId.c_str() << " not found." << std::endl << std::endl;
        return;
    }
    students.erase(iter);
    std::cout << studentId.c_str() << " removed from roster." << std::endl << std::endl;

}

std::list用作

std::list<Student> students;

void Roster::removeStudentById(std::string studentId)
{
    for (auto student = students.begin(); student != students.end();)
    {
        if (student->getStudentID() == studentId)
        {
            student = students.erase(student);
            std::cout << studentId.c_str() << " removed from roster." << std::endl << std::endl;
            return;
        }
        else
            ++student;
    }
    
    std::cout << studentId.c_str() << " not found." << std::endl << std::endl;
}

如果您的数据计数大于某些标准,例如 10 或20 ,associated contaminates则获得比.mapunordered-mapsearcheraselist


推荐阅读