c++ - 如何根据某些值删除/删除类对象的 vector

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

<分区>

P S :可能这个问题已经被问过,但我尝试了很多,而且我没有将指针与 vector 一起使用。如果解决方案是这样,请在这里告诉我如何使用指针。

我的问题:我正在创建一个 Car 类实例的 vector ,并使用了 gettersetter 方法在其中检索和推送新记录。即使我也在编辑该记录,但我不知道如何删除特定记录!我已将代码放在我自己尝试的注释中。有人可以帮我从这个 vector 中删除/删除该类的特定记录/实例吗?

提前致谢。

汽车.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;
}

最佳答案

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

您的问题本身就有答案:您需要 erase–remove idiom删除 Car来自您的 std::vector<Car> 的对象,根据您提供的 key /ID。

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


更新

C++20 确保为 all standard containers 提供统一的容器删除语义. 使用 std::erase_if (std::vector) ,OP 的代码如下所示:

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

Live Demo

关于c++ - 如何根据某些值删除/删除类对象的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50514233/

相关文章:

声明 Get 方法 const 时出现 C++ 错误

c++ 和 boost program_options 错误 : 'desc' does not name a type

c++ - OpenGL - 水波(有噪音)

javascript - 在子数组的数组中查找最大值

algorithm - 在无向无环简单图中找到最小子图

c++ - 如何使用重载运算符 [] 为左侧赋值?

python - Networkx 中 Louvain 分区的可视化

java - 从不同的包调用公共(public)类中的公共(public)类

python - 使用类实例的索引引用时会调用什么方法?

c++ - 无法使用合格枚举作为参数将类实例化为 LHS 值 (C++ VS2015)