4

Attributeプロパティを持つクラスがありますstd::string attributeNameAttribute提供された文字列にattributeName一致するインデックスを返す単純な関数を開発したいと思います。残念なことに、c++0x を自由に使用することはできず、Attributeより複雑なもののために == 演算子を既にオーバーロードしています。どんな助けでも大歓迎です、ありがとう!

編集 - 申し訳ありませんが、検索している属性のベクトルがあるかどうかがはっきりしないことに気付きましたvector<Attribute> aVec

4

3 に答える 3

9

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"; });

または、これを異なる名前で複数回行う必要がある場合は、ラムダ関数を変数として作成し、次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"));
于 2013-02-25T09:05:11.847 に答える
1

この目的を達成するために、単純に for ループを使用できます。

for (int i = 0; i<aVec.size();i++)
{
    if(aVec[i].attributeName == "yourDesiredString")
    {
        //"i" is the index of your Vector.      
    }
}
于 2016-02-06T08:00:34.270 に答える
0

boost ライブラリの bind 関数を使用することもできます。

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"
    )
);

述語クラスまたは関数を宣言せずに

于 2013-02-25T09:59:13.427 に答える