我正在尝试编写一种算法,如果项目 ID 与参数匹配,该算法将搜索项目向量并从项目向量中删除项目。请参阅下面的示例代码:
struct item{
item(int newID){id = newID;}
bool operator==(const item& other){return id = other.id;}
int id
};
std::vector<std::unique_ptr<item>> vec;
vec.push_back(std::unique_ptr<item>(new item(10));
vec.push_back(std::unique_ptr<item>(new item(15));
vec.push_back(std::unique_ptr<item>(new item(20));
因此,使用上面的代码,我希望能够搜索存储值 15 的项目,并将其从向量中删除,删除它。
我该怎么做呢?
诚然,我可能也需要温习唯一指针的使用,所以如果我的语法不正确,请随时纠正我。
我尝试过的一些解决方案如下:
void remove_item(int id){
vec.erase(
std::remove_if(
vec.begin(),
vec.end(),
[](const item& e){
return id==e.id;
}),
vec.end()
);
上面的代码产生一个错误,指出变量 id 不是 lambda 表达式的捕获列表的一部分。
其次,我尝试过:
void remove_item(item e){
auto iter = std::find(vec.begin(), vec.end(), e);
vec.erase(iter);
}
在这种情况下,上面的代码会在 == 运算符成员函数中产生类型不匹配错误。