An easy way to use 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; } 

Since this cannot be compiled on the iPhone using GCC / LLVM Clang, I want to remove the C ++ 11 functions from it. Is there any other easy way to use STL algorithms without using the C ++ 11 features? I don't want to declare a simple function like this comparison function everywhere in the code.

+1
source share
3 answers

You can try to implement a common predicate for this, something like 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 will require some additional customization, since in your case you are working with pointers, but you are getting a general idea.

+7
source

Have you tried using blocks?

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

Instead of using an anonymous function, you need to define and build a functor. You will also have to abandon 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 specifying operator ().

+2
source

All Articles