c++ - 如果元素 ID 与搜索参数匹配,如何从 std::vector 中删除元素

标签 c++ vector smart-pointers

我正在尝试编写一种算法,如果项目 ID 与参数匹配,该算法将搜索并从项目 vector 中删除项目。请参阅下面的示例代码:

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 的项目,并将其从 vector 中删除,将其删除。

我该怎么做?

诚然,我可能也需要复习一下唯一指针的使用,所以如果我的语法不正确,请随时纠正我。

我尝试过的一些解决方案如下:

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);
}

本例中的上述代码在 == 运算符成员函数中产生了类型不匹配错误。

最佳答案

您需要添加 id到 lambda 的捕获列表,以便它可以访问它。然后,您需要将传递给 lambda 的类型设为 *vec.begin() 的类型这是 std::unique_ptr<item>而不是 item

void remove_item(int id){
    vec.erase(
               std::remove_if(
                               vec.begin(),
                               vec.end(),
                               [id](const std::unique_ptr<item>& e){
                                     return id==e->id;
                               }),
               vec.end()
              );
}

从你的代码中删除所有其他无关的错误,你会得到类似的东西:

struct item {
    item(int newID) { id = newID; }
    bool operator==(const item& other) { return id == other.id; } // == here not =                                          
    int id;
};

std::vector<std::unique_ptr<item>> vec;

void remove_item(int id) {
    vec.erase(std::remove_if(
        vec.begin(), vec.end(), [id](const std::unique_ptr<item>& e) 
                                    {   return id == e->id; })
        ,vec.end());
}

int main()
{
    vec.push_back(std::unique_ptr<item>(new item(10))); // was missing a close paren
    vec.push_back(std::unique_ptr<item>(new item(15))); // was missing a close paren
    vec.push_back(std::unique_ptr<item>(new item(20))); // was missing a close paren
    remove_item(15);
    for (const auto & e : vec)
        std::cout << e->id << " ";
}

Live Example

关于c++ - 如果元素 ID 与搜索参数匹配,如何从 std::vector 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33108332/

相关文章:

c++ - shared_ptr 的 random_shuffle vector 不好(甚至危险)吗?

c++ - 除了移动语义之外,还有哪些 C++11 功能可以提高我的代码的性能?

c++ - Array 和 Vector 在编程中的区别

r - 如何从指定号码(不带名称)中仅提取号码?

iphone - 自动 C++ 内存/对象实例管理?智能指针?

c++ - shared_ptr 与 unique_ptr 在类(class)和 child 中的使用

c++ - 作为私有(private)的析构函数抛出编译时错误

c++ - 有没有办法阻止开发人员使用 std::min、std::max?

c++ operator<<的多重定义

javascript - Open Layers 3 中的样式向量