std::find_if
'u uygun bir functor ile kullanabilirsiniz. Bu örnekte, bir C++ 11 lambda kullanılır: Eğer hiçbir C++ 11 lambda desteği varsa
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);
}
, bir funktor çalışacak: Burada
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
olan bir türüdür örnekler tek bir Type
nesnesiyle çağrılabilir ve bir boole döndürür. Örneğin,
Type t("Foo"); // assume this means t.getName() is "Foo"
MatchString m("Foo");
bool b = m(t); // b is true
sonra Lambda ve Juancho tarafından kullanılan el yazısı funktor ek olarak std::find
std::vector<Type>::iterator it = find_if(v.begin(), v.end(), MatchString(myString));
Aynı ada sahip birden fazla nesne olabilir mi? Hepsini bulmak ister misin? –