【问题标题】:A Priority queue with a custom comparator in CythonCython 中带有自定义比较器的优先级队列
【发布时间】:2020-04-15 06:00:05
【问题描述】:

我知道this 的问题已经得到解答,但我似乎无法让它发挥作用。

我目前正在尝试使用 pair[double,pair[int,int]] 的 PriorityQueue 并使用该对的双精度 (pair.first) 对自身进行排序。 如果这有帮助,方法是这样的:pathfind(pair[int,int] start, pair[int,int] goal, np.ndarray grid),第一个和第二个参数是从普通 python 方法中的元组传递的,并且网格只是一个二维数组。 那么......在 Cython 中创建 pair[double,pair[int,int]] 的 PriorityQueue 并使其比较配对中的第一件事(双精度)的最佳方法是什么?

它输出的错误是这样的:error C2955: 'cpp_pq': use of alias template requires template argument list

cpp_priority_queue.hpp 代码是这样的:

#include <functional>
#include <queue>
template <class T> //Had to use this since pair wasn't getting imported correctly with <utilities>

using cpp_pq = std::priority_queue<T,std::vector<T>,std::function<bool(T,T)>>;

.pyx 代码的一部分是这样的:

cdef extern from "cpp_priority_queue.hpp":
    cdef cppclass cpp_pq:
        cpp_pq(...) except +
        void push(pair[double,pair[int,int]])
        pair[double,pair[int,int]] top()
        void pop()
        bool empty()

cdef bool compare_element(pair[double,pair[int,int]] a, pair[double,pair[int,int]] b):
    return a.first < b.first

cpdef int pathfind(pair[int,int] start, pair[int,int] goal, np.ndarray grid): # it supposed to output a 
                                                                              # list of tupples, but its 
                                                                              # an int for now until this 
                                                                              # works
    cdef cpp_pq queue = cpp_pq(compare_element)
    cdef pair[double,pair[int,int]] p = (05.7,start) # some random stuff here for testing....
    queue.push(p)
    ##nothing here till this works...
    return 0

【问题讨论】:

  • 没有回答你的问题,但是......你有什么理由不能只使用_heapq 模块?
  • @Amadan,嗨!,当它是纯 python 时,我在代码中使用了内置的 heappq,它工作得很好,但是一旦我开始创建大网格或使用多个对象,我注意到它越来越慢,因此我决定开始使用 Cython 并尽可能在 C++ 中实现以加快速度,直到出现此问题。
  • heapq 是用 Python 编写的。 _heapq(注意下划线)是用 C 编写的。它们具有完全相同的 API。您应该能够通过简单地将import heapqimport _heapq as heapq 切换来使用旧代码。
  • @Amadan 谢谢,但是......使用 _heap 的时间几乎相同,我很确定是因为我在代码中使用了 for 循环,这是主要原因让我切换到 Cython。
  • 不确定,您期望什么:您尝试使用模板类而不提供模板参数。因此,只需将 T 替换为您在 typedef 中使用的类型即可。

标签: python c++ arrays cython priority-queue


【解决方案1】:

我终于解决了这个问题,我重新启动了项目,而不是复制 .hpp 文件,我重写了它,它就像一个魅力。 出于某种原因,实用程序库一开始显示错误(红色下划线单词),所以我一直在重写代码,直到我自己设法破坏它并添加了不必要的模板。 直到我放弃并重新开始它工作的一切。

最终的 cpp_priority_queue.hpp 文件是这样的:

#include <functional>
#include <queue>
#include <utility>

using cpp_pq = std::priority_queue<std::pair<double,std::pair<int,int>>,std::vector<std::pair<double,std::pair<int,int>>>,std::function<bool(std::pair<double,std::pair<int,int>>,std::pair<double,std::pair<int,int>>)>>;

.pyx 文件格式正确,问题出在 .hpp 文件上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    相关资源
    最近更新 更多