我想搜索一个指针向量并将指针与int
。我最初的想法是使用std::find()
但我意识到我无法将指针与int
.
Example:
if(std::find(myvector.begin(), myvector.end(), 0) != myvector.end()
{
//do something
}
myvector
是一个包含指向类对象的指针的向量,即vector<MyClass*> 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。如果没有找到零,我查看是否有1。如果找到1,我输出1 .等等等等.
Use 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()
{
//...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)