问题描述
我试图找出一个很好的方法来找到一个矢量中某个对象的索引 - 通过比较一个字符串与对象中的成员字段。 pre>
像这样:find(vector.begin(),vector.end(),[object obj.getName()== myString])
我已经搜索没有成功 - 也许我不完全明白要找什么。解决方案
您可以使用与一个合适的函子。在这个例子中,使用了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())
{
//找到的元素。它是第一个匹配元素的迭代器。
//如果你真的需要索引,你也可以得到它:
auto index = std :: distance(v.begin(),it);
$ b 如果你没有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
是一个类型,其实例可以用一个类型
对象进行调用,并返回一个布尔值。例如,
类型t(Foo); //假设这意味着t.getName()是Foo
MatchString m(Foo);
bool b = m(t); // b是真的
然后你可以传递一个实例给 std ::找到
std :: vector< Type> :: iterator it = find_if(v.begin( ),v.end(),MatchString(myString));
I'm trying to figure out a nice way to find the index of a certain object in a vector - by comparing a string to a member field in the object.
Like this : find(vector.begin(), vector.end(), [object where obj.getName() == myString])
I have searched without success - maybe I don't fully understand what to look for.
解决方案 You can use std::find_if
with a suitable functor. In this example, a C++11 lambda is used:
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);
}
If you have no C++11 lambda support, a functor would work:
struct MatchString
{
MatchString(const std::string& s) : s_(s) {}
bool operator()(const Type& obj) const
{
return obj.getName() == s_;
}
private:
const std::string& s_;
};
Here, MatchString
is a type whose instances are callable with a single Type
object, and return a boolean. For example,
Type t("Foo"); // assume this means t.getName() is "Foo"
MatchString m("Foo");
bool b = m(t); // b is true
then you can pass an instance to std::find
std::vector<Type>::iterator it = find_if(v.begin(), v.end(), MatchString(myString));
这篇关于按对象属性搜索对象的矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!