Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Cython:C++;在字典中使用向量?_Python_C++_Cython - Fatal编程技术网

Python Cython:C++;在字典中使用向量?

Python Cython:C++;在字典中使用向量?,python,c++,cython,Python,C++,Cython,我使用下面的代码尝试使用C++向量: from libcpp.vector cimport vector cdef struct StartEnd: long start, end cdef vector[Sta

我使用下面的代码尝试使用C++向量:

from libcpp.vector cimport vector                                                                                                                                         

cdef struct StartEnd:
    long start, end 

cdef vector[StartEnd] vect
print(type(vect))
cdef int i
cdef StartEnd j
k = {}
k['hi'] = vect
for i in range(10):
    j.start = i 
    j.end = i + 2 
    k['hi'].push_back(j)
for i in range(10):
    print(k['hi'][i])
这里的确切功能并不重要,这只是一个虚拟程序。问题是运行此操作会生成错误:
AttributeError:'list'对象没有属性“push_back”
如果没有字典,则此操作有效,但我认为字典对于我的用例是必要的。有没有办法让这一切顺利进行


我不想来回复制向量,因为这些向量将有几千万个条目长。也许我可以将指针存储到向量中,而不是.< /p> < p>在Cython/Python边界上,C++向量自动转换为<代码>列表>代码(因此,您看到的错误消息)。Python DICT期望存储Python对象,而不是C++向量。创建一个包含C++向量的 CDEF类< /Cord>,并将其放入DICT中:

cdef class VecHolder:
   cdef vector[StartEnd] wrapped_vector

   # the easiest thing to do is add short wrappers for the methods you need
   def push_back(self,obj):
     self.wrapped_vector.push_back(obj)

cdef int i
cdef StartEnd j
k = {}
k['hi'] = VecHolder()
for i in range(10):
   j.start = i 
   j.end = i + 2 
   k['hi'].push_back(j) # note that you're calling 
       # the wrapper method here which then calls the c++ function

“如果没有字典,这是什么意思?”@RNar推测
vect.push\u back(…)
有效,但是
k['hi'])。push\u back(…)
无效。尝试使用
(k['hi'])将
k['hi]
转换为向量。push\u back(…)
,如是。回答得很好,谢谢。我通过公开wrapped_vector变量,然后执行
打印(k['hi'].wrapped_vector[I])
来完成查找部分的工作。请记住,这样做会将向量复制到临时列表中(这可能会很慢!)。在
VecHolder
上定义一个
\uuuuu getitem\uuuuuuuuuuuuuuuuuuuuuux)
以避免这种情况(尽管您仍然需要考虑如何打印
StartEnd
)。谢谢,我这样做了,效果很好。但有一件事很奇怪:当我直接使用StartEnd结构时,我通过点访问组件(例如,
j.start=I
),然而,当我从向量中获取结构时,它是一个字典,我必须这样访问:
k['hi'][I]['start']
,而不是
k['hi'][I]。start
。我还不确定这是否意味着出了什么问题(即结构已被转换为python对象,而不是保留为C结构。有什么想法吗?是的,它正在转换为与结构匹配的python字典。我没有意识到它会这样做!最大的问题是
k['hi'][I]['start']=5
实际上不会改变任何东西。我认为有两种解决方案:1)使用
wrapped_vector
(您可能需要使用两行typecast
cdef veccholder vh=k['hi'];k['hi'].wrapped_vector[I]。开始
)或者2)-您有
\uuu getitem\uuu
StartEnd
周围返回一个小包装器,它存储对
VecHolder
和索引的引用,并使用属性访问底层的
开始
结束
(有关实现,请参阅
PyPeak2
,忽略“移动”内容)。把这类事情做好,结果总是比看上去更麻烦!