您可以将std::find_if 与合适的函子一起使用。在此示例中,使用了 C++11 lambda:
std::vector<Type> v = ....;
std::string myString = ....;
auto it = find_if(v.begin(), v.end(), [&myString](const Type& obj) {return obj.getName() == myString;})
if (it != v.end())
{
// found element. it is an iterator to the first matching element.
// if you really need the index, you can also get it:
auto index = std::distance(v.begin(), it);
}
如果您没有 C++11 lambda 支持,函子可以工作:
struct MatchString
{
MatchString(const std::string& s) : s_(s) {}
bool operator()(const Type& obj) const
{
return obj.getName() == s_;
}
private:
const std::string& s_;
};
这里,MatchString 是一种类型,其实例可以使用单个 Type 对象调用,并返回一个布尔值。例如,
Type t("Foo"); // assume this means t.getName() is "Foo"
MatchString m("Foo");
bool b = m(t); // b is true
然后您可以将实例传递给std::find
std::vector<Type>::iterator it = find_if(v.begin(), v.end(), MatchString(myString));