【问题标题】:How can I erase/delete vector of class objects according to some Values [closed]如何根据某些值擦除/删除类对象的向量[关闭]
【发布时间】:2018-11-03 23:16:36
【问题描述】:

PS:可能这个问题已经被问过了,但我尝试了很多,而且我没有使用带有矢量的指针。如果解决方案是这样,请告诉我如何在此处使用指针。

我的问题:我正在创建一个包含 Car 类实例的向量,并使用 gettersetter 方法在其中检索和推送新记录。即使我也在编辑该记录,但我不知道如何删除特定记录!我已将代码放在我自己尝试的 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;
}

【问题讨论】:

标签: c++ algorithm class c++11 stdvector


【解决方案1】:

即使我也在编辑该记录,但我不知道如何删除 具体记录???我已经把代码放在我试过的cmets中 我自己,所以如果有人知道,请告诉我我该如何“删除/擦除” 来自向量类对象的特定记录?

您的问题本身就有答案:根据您提供的密钥/ID,您需要 Erase–remove idiom 从您的 std::vector &lt; Car &gt; 中删除 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());

LIVE DEMO

【讨论】:

    【解决方案2】:

    如果您不想使用 lambda 函数,可以执行以下操作

    void deleteCarVector( vector<Car>& newAllCar)
    {
        int id;
        cout<<" \n\t\t Please Enter the Id of Car to Delete Car Details :  ";
        cin>>id;
    
        auto carItr = newAllCar.begin();
    
        while(carItr != newAllCar.end())
        {
            if((*carItr)->getId==id)
            {
                delete *carItr;
                newAllCar.erase(carItr);
                break;
            }
            carItr++;
        }
    
        printCarVector(newAllCar);
    
        cout << endl;
    }
    

    【讨论】:

    • 我可以说服您用基于范围的for 替换迭代器中的whileall 吗?
    • 有不同的编码方式,您可以使用基于范围的编码,只需很少的 tweeks
    • 它给了我指针错误...
    • 您遇到的错误是什么
    猜你喜欢
    • 2022-01-13
    • 2022-11-22
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多