Cython-遍历地图

bor*_*ris 5 python cython

我想知道是否有可能直接在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
Run Code Online (Sandbox Code Playgroud)

这不会编译: Object of type 'iterator' has no attribute 'first'

我之前在cpp中使用了地图容器,但是对于此代码,我试图坚持使用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
Run Code Online (Sandbox Code Playgroud)

Dav*_*idW 9

地图迭代器没有元素firstsecond。相反,它有一个operator*返回pair引用。在C ++中,你可以使用it->first要做到这一点一气呵成,但是这句法不会用Cython工作(这是不足够的智能来决定使用->的,而不是.自己在这种情况下)。

相反,您使用cython.operator.dereference

from cython.operator cimport dereference

# ...

print(dereference(it).first)
Run Code Online (Sandbox Code Playgroud)

同样,it++可以用cython.operator.postincrement