如何根据类属性在向量中找到对象

How can I find an object in a vector based on class properties?

本文关键字:对象 向量 何根 属性      更新时间:2023-10-16

我有一个属性为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"
    )
);

不声明谓词类或函数