Search code examples
c++algorithmclassc++11stdvector

How can I erase/delete vector of class objects according to some Values


P S : May be this question has already been asked but I tried a lot and also I'm not using the pointer with vector. If the solution is that, please tell me how to use pointer here.

My Question: I'm creating a vector of Car class instances and used getter and setter methods to retrieving and pushing new records inside it. Even I'm editing that records also but I don't know how to delete particular record! I have put the code in comments which I tried by myself. could someone help me to remove/erase the particular record/ instance of the class, from this vector?

Thanks in advance.

Car.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;
}

Solution

  • [...]How can I "remove/erase" the particular record from vector class object?

    You have your answer in your question itself: you need erase–remove idiom to remove the Car objects from your std::vector<Car>, according to the key/id you provide.

    carVec.erase(std::remove_if(carVec.begin(), carVec.end()
         , [&id_to_delete](const Car& ele) {
                return ele.getnewId() == id_to_delete;
         }), 
         carVec.end()
    );
    

    Live Demo


    Updates

    C++20 ensures a uniform container erasure semantics for all standard containers. Using std::erase_if (std::vector), the OP's code would look like:

    std::erase_if(carVec, [&id_to_delete](const auto& ele) { 
        return ele.getnewId() == id_to_delete;
    });
    

    Live Demo