简体   繁体   中英

Easy way of using STL algorithms in C++

I have this code on Win32:

Actor* Scene::GetActor(const char* name)
{
    StringID actorID(name);

    auto actor = find_if(m_actors.begin(), m_actors.end(), [&](Actor* actor){return actor->GetName() == actorID;});
    return  actor != m_actors.end() ? *actor : NULL;
}

Because this couldn't be compiled on iPhone with GCC/LLVM Clang I want to removed C++11 features from it. Is there any other easy way of using STL algorithms without using C++11 features? I don't want to declare simple function like this compare function everywhere in the code.

You can try to implement a generic predicate for this, something along these lines (demo here ):

template<class C, class T, T (C::*func)() const>
class AttributeEquals {
public:
    AttributeEquals(const T& value) : value(value) {}

    bool operator()(const C& instance) {
        return (instance.*func)() == value;
    }
private:
    const T& value;
};

This would require some more tweaking, since in your case you are working with pointers, but you get the general idea.

Have you tried using Blocks?

auto actor = find_if(m_actors.begin(), m_actors.end(),
                     ^(Actor* actor){return actor->GetName() == actorID;});

Rather than using an anonymous function, you'll have to define and construct a functor. You'll also have to drop the auto keyword.

Actor* Scene::GetActor(const char* name)
{
    StringID actorID(name);
    MyFunctor funct(actorID); // move code from anon function to operator() of MyFunctor
    // Replace InputIterator with something appropriate - might use a shortening typedef
    InputIterator actor = find_if(m_actors.begin(), m_actors.end(), funct);
    return  actor != m_actors.end() ? *actor : NULL;
}

If StringID is your own class, you can make it a functor by defining operator().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM