c++ - 将一个函数的 vector + map 版本合并为一个兼容的版本

标签 c++ dictionary vector template-function

这是我为 std::map 容器和带有 Lambda 表达式的 std::vector 容器重载的两个函数。

有没有人看到一种方法来使它成为模板函数,它可以检查 Lambda 表达式的 pair 类型(在我的例子中是第二对)和常规范围类型(​​如 vector 双端队列 等)。

bool isPlayerIn(vector<Player*> players, int id) {
    vector<Player*>::iterator found = find_if(begin(players), end(players),
                                              [id] (Player* player) {
        return player->getId() == id;
        });
     return found != end(players);
}

bool isPlayerIn(map<int, Player*> players, int id) {
     map<int, Player*>::iterator found = find_if(begin(players), end(players),
                                                 [id] (pair<int, Player*> found) {
        return found.second->getId() == id;
        });
     return found != end(players);
}

最佳答案

这可以用一些 template metaprogramming 来解决,特别是类似 Boost's is_pair 的东西.这个想法是将微分从算法“下推”到仿函数。

请注意,对于您编写的类型的非常短的函数,您可能不会发现这是一个改进;对于更长的函数,涉及更复杂的算法,这将消除大量重复。

所以,您将有两个这样的类:

template<typename T, bool Pair> 
matches_id : 
    std::unary_function<T, bool>
{
    // Ctor taking id
    // operator() deciding if t.second matches id
};

template<typename T>
matches_id<T, false> : 
    std::unary_function<T, bool>
{
    // Ctor taking id
    // operator() deciding if t itself matches id
};

在您的代码中,您将对类型的对象使用 find_if

matches_id<T, is_pair<T>::value>

关于c++ - 将一个函数的 vector + map 版本合并为一个兼容的版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34858435/

相关文章:

r - 有没有一种有效的方法来检查 R 字符向量是否包含相同的元素?

c++ - 如何修复 istringstream 编译器错误?

c++ - 我怎样才能找出哪个插槽连接到我的信号?

C++ 套接字 recv() 系统调用返回 -1

c++ - 为什么我不能 push_back 到 const 元素的 vector ?

vector - 获取向量的最后一个元素并将其推送到同一个向量

C++ 使用在类定义中声明的变量在同一类定义中声明不同的变量

c++ - 实现 '<' 运算符

python - 从Python中的列表创建字典

ios - iOS 6 中 Apple map 方案 : how to show a callout/pin?