在列表中查找指针

Finding a pointer in a list

我想在包含指针的列表中找到一个元素。

这个问题与find an item in a list of pointers非常相似,但我尝试用不同的方式来做,它似乎有效。

在链接的问题中,人们建议使用 find_if、lambda 和类似的东西。将查找的指针传递给 std::find 还不够吗?我错过了什么吗?

这是我用于测试的代码,它似乎可以正常工作。我 运行 它使用不同的参数,我得到了预期的结果。

typedef struct _C
{
     int num;
     int name;
} C;

int main(void)
{
    C *new_c = new C();
    new_c->num = 2;
    new_c->name = 1;

    C *new_b = new C();
    new_b->num = 3;
    new_b->name = 32;

    C *new_d = new C();
    new_d->num = 1;
    new_d->num = 11;

    std::list<C *> list;
    list.push_front(new_b);
    list.push_front(new_c);

    std::list<C *>::iterator del_new =
        std::find(list.begin(), list.end(), new_c);

    if(del_new != list.end())
        std::cout << "Found" << std::endl;
    else
        std::cout << "Not found" << std::endl;

你的代码是正确的。查找指针与查找整数类型相同,使用列表 std::find 是查找指针的好方法(时间复杂度 o(n))。