[英]std::find() on a vector of pointers
I want to search through a vector of pointers to and compare the pointers to an int
. 我想搜索一个指针向量并比较指向
int
的指针。 My initial idea was to use std::find()
but i realized that I cannot compare a pointer to an int
. 我最初的想法是使用
std::find()
但我意识到我无法比较指向int
的指针。
Example: 例:
if(std::find(myvector.begin(), myvector.end(), 0) != myvector.end()
{
//do something
}
myvector
is a vector containing pointers to a class object, ie, vector<MyClass*> myvector
. myvector
是一个包含指向类对象的指针的向量,即vector<MyClass*> myvector
。 MyClass
contains a method getValue()
which will return an integer value and I basically want to go through the vector and check each object's getValue()
return value to determine what i do. MyClass
包含一个方法getValue()
,它将返回一个整数值,我基本上想要通过向量并检查每个对象的getValue()
返回值来确定我做了什么。
Using the previous example: 使用前面的示例:
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
}
Its almost like an absolute condition where if any pointer's value in my vector is a 0, i output zero, i output 0. If no zero is found, i look to see if there is a 1. If 1 is found, i output 1. Etc, etc.. 它几乎像一个绝对条件,如果我的向量中的任何指针值是0,我输出零,我输出0.如果没有找到零,我看看是否有1.如果找到1,我输出1等等。
What you want is std::find_if
and a custom compare function/functor/lambda. 你想要的是
std::find_if
和自定义比较函数/ functor / lambda。 With the custom comparator you can call the correct function to do the comparison. 使用自定义比较器,您可以调用正确的函数进行比较。 Something like
就像是
std::find_if(myvector.begin(), myvector.end(), [](MyClass* e) { return e->getValue() == 0; })
Use std::find_if()
instead. 请改用
std::find_if()
。 The other answers show how to use a lambda for the predicate, but that only works in C++11 and later. 其他答案显示了如何将lambda用于谓词,但这只适用于C ++ 11及更高版本。 If you are using an earlier C++ version, you can do this instead:
如果您使用的是早期的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()
{
//...
}
You need to tell the compiler that you want to call getValue()
on each pointer, and that's the thing you're searching for. 您需要告诉编译器您要在每个指针上调用
getValue()
,这就是您要搜索的内容。 std::find()
is only for matching values, for anything more complicated, there's std::find_if
: std::find()
仅用于匹配值,对于更复杂的东西,有std::find_if
:
std::find_if(myvector.begin(), myvector.end(),
[](const MyClass* c) { return c->getValue() == 0; }
);
You can use std::find_if
which relies on a predicate rather than a value 您可以使用
std::find_if
,它依赖于谓词而不是值
if(std::find_if(myvector.begin(), myvector.end(), [](MyClass* my) { return my->getValue() == 0; }) != myvector.end()
{
//Output 0
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.