The Unfun Cat
The Unfun Cat

Reputation: 31948

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

I have two sorted vectors that I'd like to merge. Is it possible to do this simply with c++ std::merge or do I need to roll my own? I could not find merge in libcpp.

Upvotes: 1

Views: 57

Answers (1)

ead
ead

Reputation: 34347

Not all c++-methods are wrapped in Cython's cpplib, but using the already wrapped methods as blueprint, it is easy to wrap the missing functionality - there is no need to reimplement the algorithm (no matter how easy)

For example:

%%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)

leads to the expected output, when the cython-extension is imported:

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

Upvotes: 2

Related Questions