我如何使用 c++ std::merge 在 cython 中合并两个排序的向量?

How can I use c++ std::merge to merge two sorted vectors in cython?

我有两个排序的向量要合并。是否可以简单地使用 c++ std::merge 来做到这一点,还是我需要自己动手?我在 libcpp 中找不到合并。

并不是所有的 c++ 方法都包装在 Cython 的 cpplib 中,但是使用 already wrapped methods 作为蓝图,很容易包装缺失的功能——不需要重新实现算法(无论多么容易)

例如:

%%cython  --cplus 
from libcpp.vector cimport vector

# wrap it yourself!
cdef extern from "<algorithm>" namespace "std" nogil:
   OutputIter merge[InputIter1, InputIter2, OutputIter] (InputIter1 first1, InputIter1 last1,
                        InputIter2 first2, InputIter2 last2,
                        OutputIter result)

# for ilustration purposes:
cdef vector[int] v1=[1,3,5]
cdef vector[int] v2=[2,4,6]
cdef vector[int] out = vector[int](6)

merge(v1.begin(), v1.end(), v2.begin(), v2.end(), out.begin())

print(out)

当导入 cython 扩展时,会产生预期的输出:

[1,2,3,4,5,6]