Cython - 遍历地图

Cython - iterate through map

我想知道是否可以直接在 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 中使用过地图容器,但是对于这段代码,我试图坚持 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

地图迭代器没有元素 firstsecond。相反,它有一个 operator* 其中 returns 一个 pair 引用。在 C++ 中,您可以使用 it->first 一次性完成此操作,但该语法在 Cython 中不起作用(而且它不够智能,无法决定使用 -> 而不是 .在这种情况下本身)。

你使用 cython.operator.dereference:

from cython.operator cimport dereference

# ...

print(dereference(it).first)

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

来完成