Cython:无法分配给二维向量
Cython: unable to assign to 2d vector
我有以下内容:
# distutils: language = c++
from libcpp.vector cimport vector
def foo():
cdef vector[vector[int]] matrix
matrix.reserve(100);
matrix[0] = [1,2,3]
print(matrix)
foo()
它打印出一个空列表;我希望它打印出一个第一个元素为 [1,2,3]
的向量。
Setup.py 脚本:
from setuptools import setup
from Cython.Build import cythonize
setup(
name='myfile',
ext_modules=cythonize("my_file.pyx"),
zip_safe=False,
)
我该如何解决这个问题?
您应该使用 matrix.resize(100)
而不是 matrix.reserve(100)
。 std::vector<>::reserve
不会改变向量的大小 - 它只保留内存,因此不需要进一步(多次)重新分配:
%%cython
...
matrix.reserve(100)
print(matrix.size()) # prints 0
matrix.resize(100)
print(matrix.size()) # prints 100
...
目前 matrix[0] = [1,2,3]
是未定义的行为(大小为 0
- 没有元素)并且你很不幸它不会因超出范围访问而崩溃。
我有以下内容:
# distutils: language = c++
from libcpp.vector cimport vector
def foo():
cdef vector[vector[int]] matrix
matrix.reserve(100);
matrix[0] = [1,2,3]
print(matrix)
foo()
它打印出一个空列表;我希望它打印出一个第一个元素为 [1,2,3]
的向量。
Setup.py 脚本:
from setuptools import setup
from Cython.Build import cythonize
setup(
name='myfile',
ext_modules=cythonize("my_file.pyx"),
zip_safe=False,
)
我该如何解决这个问题?
您应该使用 matrix.resize(100)
而不是 matrix.reserve(100)
。 std::vector<>::reserve
不会改变向量的大小 - 它只保留内存,因此不需要进一步(多次)重新分配:
%%cython
...
matrix.reserve(100)
print(matrix.size()) # prints 0
matrix.resize(100)
print(matrix.size()) # prints 100
...
目前 matrix[0] = [1,2,3]
是未定义的行为(大小为 0
- 没有元素)并且你很不幸它不会因超出范围访问而崩溃。