【问题标题】:Easy way of using STL algorithms in C++在 C++ 中使用 STL 算法的简单方法
【发布时间】:2011-10-07 21:36:56
【问题描述】:

我在 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;
}

因为无法在 iPhone 上使用 GCC/LLVM Clang 编译它,所以我想从中删除 C++11 功能。有没有其他简单的方法可以在不使用 C++11 特性的情况下使用 STL 算法?我不想在代码中到处声明像这样的比较函数这样的简单函数。

【问题讨论】:

  • 不是您问题的直接答案(我会把它留给其他人),但如果您经常进行查找,也许您需要不同的数据结构,例如 std::map。跨度>
  • 我们是否应该假设m_actors 类似于std::vector<Actor*>(看起来是这样)?
  • 您是否尝试过包含 Apple LLVM 3.0 的 Xcode 4.2?
  • @trojanfoe/@Roland Illig 启用了 C++0x 的 LLVM 3.0 我有:解析错误...

标签: c++ c++11


【解决方案1】:

您可以尝试为此实现一个通用谓词,类似于以下内容(演示 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;
};

这需要更多的调整,因为在你的情况下你正在使用指针,但你明白了一般的想法。

【讨论】:

【解决方案2】:

您是否尝试过使用 Blocks?

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

【讨论】:

  • 不,但我会尝试。为此 +1
【解决方案3】:

您必须定义和构造函子,而不是使用匿名函数。您还必须删除 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() 使其成为仿函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-02
    • 2021-03-27
    • 2011-01-13
    • 2017-06-06
    • 2011-07-27
    • 1970-01-01
    • 2013-11-13
    • 2022-12-11
    相关资源
    最近更新 更多