在列表中查找指针

时间:2015-07-08 09:09:50

标签: c++ list pointers find

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

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

在链接问题中,人们建议使用find_if,lambdas和类似的东西。将搜索到的指针传递给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;

1 个答案:

答案 0 :(得分:0)

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