c++ - 如何使用 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;
}
解决方案
如果您的解决方案需要删除一些项目,请尝试使用std::list
or std::unordered_map
orstd::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
则获得比.map
unordered-map
search
erase
list
推荐阅读
- google-chrome-extension - 创建功能,如谷歌翻译 chrome 扩展
- python - 使用带有 bs4 和或 json 的请求
- python - Python - 跟踪可以由另一个进程重命名的日志文件
- java - 问题错误检查代码
- asp.net - Gridview 删除链接按钮未触发 RowDeleting 事件
- c# - Visual Studio 2015 更新 3 无法读取 NuGet 包
- c++ - 增加迭代变量背后的直觉?
- javascript - 仅使用一个循环对随机数组进行排序,无需排序功能
- php - 根据数据透视表列获取模型数据
- random - 如何在 Ada 中生成浮点随机数?