std :: find()指针向量

时间:2016-02-18 19:00:18

标签: c++ pointers vector find

我想搜索一个指针向量并比较指向int的指针。我最初的想法是使用std::find(),但我意识到我无法比较指向int的指针。

示例:

if(std::find(myvector.begin(), myvector.end(), 0) != myvector.end()
{
   //do something
}

myvector是一个包含指向类对象的指针的向量,即vector<MyClass*> myvectorMyClass包含一个方法getValue(),它将返回一个整数值,我基本上想要浏览向量并检查每个对象的getValue()返回值以确定我的操作。

使用前面的例子:

if(std::find(myvector.begin(), myvector.end(), 0) != myvector.end()
{
   //Output 0
}
else if(std::find(myvector.begin(), myvector.end(), 1) != myvector.end()
{
   //Output 1
}
else if(std::find(myvector.begin(), myvector.end(), 2) != myvector.end()
{
   //Output 2
}

它几乎就像一个绝对条件,如果我的向量中的任何指针值都是0,我输出零,我输出0.如果没有找到零,我看看是否有一个1.如果发现1,我输出1.等等。

4 个答案:

答案 0 :(得分:6)

你想要的是std::find_if和自定义比较函数/ functor / lambda。使用自定义比较器,您可以调用正确的函数进行比较。像

这样的东西
std::find_if(myvector.begin(), myvector.end(), [](MyClass* e) { return e->getValue() == 0; })

答案 1 :(得分:5)

请改用std::find_if()。其他答案显示了如何将lambda用于谓词,但这只适用于C ++ 11及更高版本。如果您使用的是早期的C ++版本,则可以改为:

struct isValue
{
    int m_value;

    isValue(int value) : m_value(value) {}

    bool operator()(const MyClass *cls) const
    {
        return (cls->getValue() == m_value);
    }
};

...

if (std::find_if(myvector.begin(), myvector.end(), isValue(0)) != myvector.end()
{
    //...
}

答案 2 :(得分:1)

您需要告诉编译器您要在每个指针上调用getValue(),这就是您要搜索的内容。 std::find()仅用于匹配值,对于更复杂的值,std::find_if

std::find_if(myvector.begin(), myvector.end(),
    [](const MyClass* c) { return c->getValue() == 0; }
);

答案 3 :(得分:0)

您可以使用List<Runnable> runnables = list.stream() .<Runnable> map(consumer -> () -> consumer.accept(value)) .collect(Collectors.toList()); ,它依赖于谓词而不是值

std::find_if
相关问题