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

use*_*732 3 c++ vector find

我有一个Attribute属性的班级std::string attributeName.我想开发一个简单的函数,它返回Attribute具有attributeName匹配的字符串的索引.不幸的限制包括:我没有c ++ 0x,而且我已经重载了Attribute==运算符以获得更复杂的东西.任何帮助将不胜感激,谢谢!

编辑 - 我很抱歉,我意识到我正在搜索的属性向量并不清楚vector<Attribute> aVec.

Som*_*ude 8

使用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"
}
Run Code Online (Sandbox Code Playgroud)

要在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"; });
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要使用不同的名称多次执行此操作,请将lambda函数创建为变量,并std::bind在调用中使用std::find_if:

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"));
Run Code Online (Sandbox Code Playgroud)