c++ - 如何根据某些值擦除/删除类对象的向量
问题描述
PS:可能这个问题已经被问过了,但我尝试了很多,而且我没有使用带有矢量的指针。如果解决方案是这样,请告诉我如何在此处使用指针。
我的问题:我正在创建一个Car
类实例的向量,并使用getter
和setter
方法在其中检索和推送新记录。即使我也在编辑该记录,但我不知道如何删除特定记录!我已将代码放在我自己尝试过的注释中。有人可以帮我从这个向量中删除/擦除类的特定记录/实例吗?
提前致谢。
汽车.cpp
#include "Car.h"
#include "global.h"
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
int cid =1;
string Name;
float Price;
//In this function I want to delete the records
void deleteCarVector( vector<Car>& newAllCar)
{
int id;
cout << "\n\t\t Please Enter the Id of Car to Delete Car Details : ";
cin >> id;
//replace (newAllCar.begin(), newAllCar.end(),"a","b");
unsigned int size = newAllCar.size();
for (unsigned int i = 0; i < size; i++)
{
if(newAllCar[i].getId() == id)
{
cout << "Current Car Name : "<<newAllCar[i].getName() << "\n";
// Here Exactly the problem!
// delete newAllCar[i];
// newAllCar.erase(newAllCar[i].newName);
// newAllCar.erase(remove(newAllCar.begin(),newAllCar.end(),newAllCar.at(i).getId()));
}
}
printCarVector(newAllCar);
cout << endl;
}
解决方案
即使我也在编辑该记录,但我不知道如何删除 特定记录???我已将代码放在我自己尝试过的注释中,所以如果有人知道,请告诉我如何 从矢量类对象中“删除/擦除”特定记录?
您的问题本身就有答案:根据您提供的密钥/ID,您需要Erase-remove idiom从您的 中删除Car
对象。std::vector < Car >
carVec.erase(std::remove_if(carVec.begin(), carVec.end(), [&id_to_delete](const Car& ele)->bool
{
return ele.getnewId() == id_to_delete;
}), carVec.end());
推荐阅读
- javascript - 从另一个 js 文件调用异步函数
- rest - 动态计算资源的 REST API(尚不存在)
- c++ - QT中外部窗口的X,Y,W,H
- macos - Tmux 发送前缀在 iTerm2 集成模式下不起作用
- c# - 无法附加到 Visual Studio 2003 中的进程
- r - 数据时间戳为分钟,每 5、30 分钟保存一次数据是实现它的最佳方式
- excel - 近似搜索不同工作表上另一个列表范围内的单元格值列表
- json - Charts.js - 来自 JSON 的 onComplete javascript 函数
- bitcoin - 不接收比特币进入 bitcoind 守护进程
- apache-spark - Spark UI 输入列值太高