Cython,关于向量(大小)构造函数的混淆

Nim*_*z14 3 c++ python cython

编辑:仅供参考,现在遇到此问题的任何人只需使用 pybind11,不要在此(cython 内容)上浪费时间

似乎定义vector变量的唯一方法是

cdef std::vector[int]* vec=new vector[int](<size>)

我的想法正确吗?这是示例代码,如果我编译并运行此 Python 最终会崩溃(VS2015,Python 3.5)。

from libcpp.vector cimport vector
def test():
    cdef vector[int]* vec = new vector[int](5)
    cdef int i
    for i in range(5):
        print(vec[i])

    del vec
Run Code Online (Sandbox Code Playgroud)

我想要一个具有一定大小的二维向量。我该怎么做?可不可能是:

cdef std::vector[std::vector[int]]* vec=new vector[vector[int](<size1>)](<size2>)

Ami*_*ory 5

虽然官方的例子展示了如何在堆上创建这些东西,但出于某种原因,这并不是真正必要的。此代码构建:

from libcpp.vector cimport vector                                                                                                                                                                          


ctypedef vector[int] int_vec                                                        
ctypedef vector[int_vec] int_vec_vec                                                


def test():                                                                         
    cdef int_vec v                                                                  
    v = int_vec(5)                                                                  

    cdef int_vec_ve vv                                                              
    vv = int_vec_vec(5, v)   
Run Code Online (Sandbox Code Playgroud)

它构建了一个 5X5 的 int 向量向量。