C++ 指针向量上的std::find()
我想搜索指向的指针向量,并将指针与C++ 指针向量上的std::find(),c++,pointers,vector,find,C++,Pointers,Vector,Find,我想搜索指向的指针向量,并将指针与int进行比较。我最初的想法是使用std::find(),但我意识到我无法将指针与int进行比较 例如: if(std::find(myvector.begin(), myvector.end(), 0) != myvector.end() { //do something } myvector是一个包含指向类对象指针的向量,即vector myvectorMyClass包含一个方法getValue(),该方法将返回一个整数值,我基本上希望遍历该向量并检
int
进行比较。我最初的想法是使用std::find()
,但我意识到我无法将指针与int
进行比较
例如:
if(std::find(myvector.begin(), myvector.end(), 0) != myvector.end()
{
//do something
}
myvector
是一个包含指向类对象指针的向量,即vector myvector
MyClass
包含一个方法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,我输出0。如果没有找到零,我将查看是否有1。如果找到1,则输出1。Etc,Etc.您可以使用依赖谓词而不是值的
std::find_if
if(std::find_if(myvector.begin(), myvector.end(), [](MyClass* my) { return my->getValue() == 0; }) != myvector.end()
{
//Output 0
}
您需要的是
std::find_if
和一个自定义比较函数/functor/lambda。使用自定义比较器,您可以调用正确的函数进行比较。差不多
std::find_if(myvector.begin(), myvector.end(), [](MyClass* e) { return e->getValue() == 0; })
您需要告诉编译器您要在每个指针上调用
getValue()
,这就是您要搜索的内容std::find()
仅用于匹配值,对于更复杂的内容,有:
改用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()
{
//...
}
<代码> GETValue>>()/Cord>是一个< C++ >代码>函数,谢谢您提供的解决方案,因为我使用了C++的早期版本。你能解释一下
struct isValue
吗?我知道该在哪里使用它。isValue
struct被用作std::find_if()
谓词:std::find_if(…,isValue(0))
。使用所需的比较值构造结构的新实例,然后将该实例传递给std::find_if()
。谓词接受可以使用result=predicate(params)
语法调用的任何内容,包括普通函数、具有重写的运算符()的对象、lambdas等。我得到以下错误:错误:将'const MyClass'作为'char MyClass::getValue()'的'this'参数传递会丢弃限定符[-fppermissive]
我几乎复制了你写的内容。如果getValue()
未声明为MyClass
的const
方法(例如:int-getValue()const
),则从bool操作符()
的cls
参数中删除const
,例如:bool操作符()(MyClass*cls)常数
。
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()
{
//...
}