无法从指针初始化 C++ 向量

Not possible to initialize C++ vector from pointer

我想使用

初始化 C++ STL 向量
template<class InputIt>
std::vector(InputIt first, InputIt last);

Cython 中的构造函数。这是一个简单的例子:

from libcpp.vector cimport vector
import numpy as np
cimport numpy as cnp
cnp.import_array()

def foo(double[::1] a):
    cdef vector[double] vec = vector[double](&a[0], &a[0] + a.size)
    # do something with vec..

但是,这会产生错误消息

from libcpp.vector cimport vector

def foo(double[::1] a):
    cdef vector[double] vec = vector[double](&a[0], &a[0] + a.size)
                                                   ^
------------------------------------------------------------

.ipython/cython/_cython_magic_c522d88d9553084771dd501620335f85a93b04ae.pyx:5:52: Cannot convert 'double *' to Python object

Error compiling Cython file:
------------------------------------------------------------
...

from libcpp.vector cimport vector

def foo(double[::1] a):
    cdef vector[double] vec = vector[double](&a[0], &a[0] + a.size)
                                            ^
------------------------------------------------------------

.ipython/cython/_cython_magic_c522d88d9553084771dd501620335f85a93b04ae.pyx:5:45: Cannot assign type 'double *' to 'size_type

知道我做错了什么吗?

如评论中所述,Cython 中没有您想要的构造函数。 AFAIK,Cython 还不支持模板化构造函数。作为解决方法,您可以使用 .assign(),即:

from libcpp.vector cimport vector

def foo(double[::1] a):
    cdef vector[double] vec
    vec.assign(&a[0], &a[0] + <size_t>a.size)
    # do something with vec..