cython cannot insert into deque using iterators

cython cannot insert into deque using iterators

Problem Description:

I am wondering if this is a bug or I am doing something wrong:

from libcpp.deque cimport deque as cdeque

cdef cdeque[int] dq1, dq2

dq1.push_back(0); dq1.push_back(1)
dq2.push_back(2); dq2.push_back(3)
dq1.insert(dq1.begin(), dq2.begin(), dq2.end())

The above code gives me 2 similar errors at compile time: Cannot convert ‘iterator’ to Python object. Each error pointing at dq2.begin() and dq2.end().
When inserting only an int it seems to work but not with iterators.
Any ideas?

Solution – 1

This was a bug in Cython versions prior to 3.0 (see this PR).

On an prior version, we have the following options

A: wrap insert, e.g.

....
cdef extern from *:
    """
    template <typename T, typename It>
    void insert(T& dest, const It& begin, const It& end){
        dest.insert(dest.begin(), begin, begin)
    }
    """
    void insert[T, It](T& dest, const It& begin, const It& end)  
...
insert(dq1, dq2.begin(), dq2.end())

B: changing/patching libcpp/deque.pxd in the local installation from

void insert(iterator, input_iterator, input_iterator)

to correct

void insert[InputIt](iterator, InputIt, InputIt) except +

This however, will not help if pyx-files needs to be build somewhere else until Cython 3.0 isn’t released/used.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject