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

Cython, confusion regarding the vector (size) constructor

本文关键字:大小 构造函数 向量 于向量 Cython      更新时间:2023-10-16

编辑:仅供参考,现在遇到此问题的任何人只需使用 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

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

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

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

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)   

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