简体   繁体   English

在C ++中使用STL算法的简单方法

[英]Easy way of using STL algorithms in C++

I have this code on Win32: 我在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. 由于无法在使用GCC / LLVM Clang的iPhone上进行编译,因此我想从中删除C ++ 11功能。 Is there any other easy way of using STL algorithms without using C++11 features? 在不使用C ++ 11功能的情况下,还有其他使用STL算法的简便方法吗? 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. 您还必须删除auto关键字。

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(). 如果StringID是您自己的类,则可以通过定义operator()使其成为函子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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