首页 > 解决方案 > 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

这不会编译: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

标签: pythoncython

解决方案


地图迭代器没有元素firstsecond. 相反,它有一个operator*返回pair引用。在 C++ 中,您可以it->first一次性完成此操作,但该语法在 Cython 中不起作用(在这种情况下,它还不够聪明,无法决定使用它->来代替.它自己)。

相反,您使用cython.operator.dereference

from cython.operator cimport dereference

# ...

print(dereference(it).first)

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


推荐阅读