[英]Easy way of using STL algorithms in C++
我在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;
}
由於無法在使用GCC / LLVM Clang的iPhone上進行編譯,因此我想從中刪除C ++ 11功能。 在不使用C ++ 11功能的情況下,還有其他使用STL算法的簡便方法嗎? 我不想在代碼中的任何地方都聲明簡單的函數,例如比較函數。
你可以嘗試實現這一通用的謂詞,東西沿着這些線路(演示這里 ):
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;
};
這將需要更多的調整,因為在您的情況下,您正在使用指針,但是您已經有了一般的想法。
您是否嘗試過使用積木?
auto actor = find_if(m_actors.begin(), m_actors.end(),
^(Actor* actor){return actor->GetName() == actorID;});
不必使用匿名函數,而必須定義和構造函子。 您還必須刪除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;
}
如果StringID是您自己的類,則可以通過定義operator()使其成為函子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.