C++ 按对象属性搜索对象向量

C++ 按对象属性搜索对象向量,c++,gcc,stl,std,C++,Gcc,Stl,Std,我正试图找到一种很好的方法来找到向量中某个对象的索引——将字符串与对象中的成员字段进行比较 像这样: find(vector.begin(), vector.end(), [object where obj.getName() == myString]) 我的搜索没有成功-也许我不完全明白要寻找什么。您可以使用合适的函子。在本例中,使用了C++11 lambda: std::vector<Type> v = ....; std::string myString = ....; au

我正试图找到一种很好的方法来找到向量中某个对象的索引——将字符串与对象中的成员字段进行比较

像这样:

find(vector.begin(), vector.end(), [object where 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())
{
  // 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);
}
这里,
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));
std::vector::iterator it=find_if(v.begin()、v.end()、MatchString(myString));

除了juancho使用的Lambda和手写函子之外,您还可以使用
boost::bind
(C++03)或
std::bind
(C++11)和一个简单的函数:

bool isNameOfObj(const std::string& s, const Type& obj)
{ return obj.getName() == s; }

//...
std::vector<Type>::iterator it = find_if(v.begin(), v.end(), 
  boost::bind(&isNameOfObj, myString, boost::placeholders::_1));
这只是为了完整性。在C++11中,我更喜欢Lambdas,在C++03中,我只会在比较函数本身已经存在的情况下使用bind。如果不是,则首选函子


PS:由于C++11没有多态/模板化的lambda,bind仍然在C++11中占有一席之地,例如,如果参数类型未知、难以拼写或不容易推断。

一个简单的迭代器可能会有所帮助

typedef std::vector<MyDataType> MyDataTypeList;
// MyDataType findIt should have been defined and assigned 
MyDataTypeList m_MyObjects;
//By this time, the push_back() calls should have happened
MyDataTypeList::iterator itr = m_MyObjects.begin();
while (itr != m_MyObjects.end())
{
  if(m_MyObjects[*itr] == findIt) // any other comparator you may want to use
    // do what ever you like
}
typedef std::vector MyDataTypeList;
//应已定义并分配MyDataType findIt
MyDataTypeList m_MyObjects;
//此时,push_back()调用应该已经发生了
MyDataTypeList::迭代器itr=m_MyObjects.begin();
while(itr!=m_MyObjects.end())
{
if(m_MyObjects[*itr]==findIt)//您可能要使用的任何其他比较器
//你喜欢做什么
}

如果使用函子,则需要使用
find\u。如何在两个对象容器中搜索匹配的成员变量?是否可以有多个同名对象?您想找到所有的成员变量吗?如何在两个对象容器中搜索匹配的成员变量?while循环中不应该有++itr吗?
std::vector<Type>::iterator it = find_if(v.begin(), v.end(), 
  boost::bind(&Type::isName, boost::placeholders::_1, myString));
typedef std::vector<MyDataType> MyDataTypeList;
// MyDataType findIt should have been defined and assigned 
MyDataTypeList m_MyObjects;
//By this time, the push_back() calls should have happened
MyDataTypeList::iterator itr = m_MyObjects.begin();
while (itr != m_MyObjects.end())
{
  if(m_MyObjects[*itr] == findIt) // any other comparator you may want to use
    // do what ever you like
}