【发布时间】:2018-11-03 23:16:36
【问题描述】:
PS:可能这个问题已经被问过了,但我尝试了很多,而且我没有使用带有矢量的指针。如果解决方案是这样,请告诉我如何在此处使用指针。
我的问题:我正在创建一个包含 Car 类实例的向量,并使用 getter 和 setter 方法在其中检索和推送新记录。即使我也在编辑该记录,但我不知道如何删除特定记录!我已将代码放在我自己尝试的 cmets 中。有人可以帮我从这个向量中删除/擦除类的特定记录/实例吗?
提前致谢。
汽车.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;
}
【问题讨论】:
-
请edit 将您的代码缩减为您的问题的minimal reproducible example。您当前的代码包含许多与您的问题无关的内容 - 一个最小样本通常看起来类似于一个好的单元测试:只执行一项任务,并为可重复性指定输入值。
-
newAllCar.erase(i);应该可以解决问题。祝你好运! -
投票关闭作为stackoverflow.com/questions/875103/… OP 的副本没有指定很多细节,因此任何答案都必须针对一般情况,其他问题已经涵盖。
标签: c++ algorithm class c++11 stdvector