如何根据类属性在向量中找到对象
How can I find an object in a vector based on class properties?
我有一个属性为std::string attributeName
的类Attribute
。我想开发一个简单的函数,返回Attribute
的索引,该索引具有与所提供的字符串匹配的attributeName
。不幸的限制包括:我没有c++0x,而且我已经为更复杂的事情重载了Attribute
==运算符。任何帮助都将不胜感激,谢谢!
edit-非常抱歉,我意识到不清楚我正在搜索的属性向量。vector<Attribute> aVec
。
将std::find_if
与自定义函数对象一起使用:
class FindAttribute
{
std::string name_;
public:
FindAttribute(const std::string& name)
: name_(name)
{}
bool operator()(const Attribute& attr)
{ return attr.attributeName == name_; }
};
// ...
std::vector<Attribute> attributes;
std::vector<Attribute>::iterator attr_iter =
std::find_if(attributes.begin(), attributes.end(),
FindAttribute("someAttrName"));
if (attr_iter != attributes.end())
{
// Found the attribute named "someAttrName"
}
要在C++11中实现这一点,实际上并没有什么不同,只是您显然不需要函数对象,或者必须声明迭代器类型:
std::vector<Attribute> attributes;
// ...
auto attr_iter = std::find_if(std::begin(attributes), std::end(attributes),
[](const Attribute& attr) -> bool
{ return attr.attributeName == "someAttrName"; });
或者,如果需要使用不同的名称多次执行此操作,请将lambda函数创建为变量,并在对std::find_if
:的调用中使用std::bind
auto attributeFinder =
[](const Attribute& attr, const std::string& name) -> bool
{ return attr.attributeName == name; };
// ...
using namespace std::placeholders; // For `_1` below
auto attr_iter = std::find_if(std::begin(attributes), std::end(attributes),
std::bind(attributeFinder, _1, "someAttrName"));
您可以简单地使用for循环来达到此目的:
for (int i = 0; i<aVec.size();i++)
{
if(aVec[i].attributeName == "yourDesiredString")
{
//"i" is the index of your Vector.
}
}
您还可以使用boost库中的绑定函数:
std::vector<Attribute>::iterator it = std::find_if(
aVec.begin(),
aVec.end(),
boost::bind(&Attribute::attributeName, _1) == "someValue"
);
或C++11绑定函数:
std::vector<Attribute>::iterator it = std::find_if(
aVec.begin(),
aVec.end(),
std::bind(
std::equal_to<std::string>(),
std::bind(&Attribute::attributeName, _1),
"someValue"
)
);
不声明谓词类或函数
相关文章:
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- 从多个源构造一个对象,包括一个对象向量
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 对象 C++ 向量的 STL 容器
- 初始化C++中的对象向量
- 从自定义类获取对象向量中的 max 元素
- 如何在 c++ 中打印存档中的对象向量
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 尝试重载输出运算符时,我无法遍历对象向量
- 如何在C++中打印对象向量的内容
- 打印出对象向量中的每个元素C++
- 在 c++ 的构造函数中分配对象向量时出错
- 遍历对象向量,并找到与从文本文件中提取的对象匹配的变量
- 对象向量是否在堆或堆栈上分配C++?
- 基于不同字段的对象向量的排序功能
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 用rapidjson读取子对象向量
- 尝试使用比较运算符对对象向量进行排序
- 如何用对象向量重载 cin(>>)
- 如何将某个元素从shared_ptr擦除到对象向量?