我想知道这是否有可能直接在Cython代码(即.pyx中)中迭代一个映射。以下是我的例子:
import cython
cimport cython
from licpp.map import map as mapcpp
def it_through_map(dict mymap_of_int_int):
# python dict to map
cdef mapcpp[int,int] mymap_in = mymap_of_int_int
cdef mapcpp[int,int].iterator it = mymap_in.begin()
while(it != mymap.end()):
# let's pretend here I just want to print the key and the value
print(it.first) # Not working
print(it.second) # Not working
it ++ # Not working这不编译:Object of type 'iterator' has no attribute 'first'
我以前在cpp中使用了map容器,但是对于这个代码,我试图坚持使用cython/python,这里有可能吗?
由DavidW解析,这里是代码的一个工作版本,下面是DavidW的答案:
import cython
cimport cython
from licpp.map import map as mapcpp
from cython.operator import dereference, postincrement
def it_through_map(dict mymap_of_int_int):
# python dict to map
cdef mapcpp[int,int] mymap_in = mymap_of_int_int
cdef mapcpp[int,int].iterator it = mymap_in.begin()
while(it != mymap.end()):
# let's pretend here I just want to print the key and the value
print(dereference(it).first) # print the key
print(dereference(it).second) # print the associated value
postincrement(it) # Increment the iterator to the net element发布于 2018-08-04 14:03:36
映射迭代器没有元素first和second。相反,它有一个operator*,它返回一个pair引用。在C++中,您可以一次使用it->first来完成这一任务,但是这种语法在Cython中不起作用(而且在本例中,它还不够聪明,无法决定使用->而不是.本身)。
相反,您使用cython.operator.dereference
from cython.operator cimport dereference
# ...
print(dereference(it).first)类似地,it++可以用cython.operator.postincrement来完成
https://stackoverflow.com/questions/51686143
复制相似问题