首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Cython -遍历map

Cython -遍历map
EN

Stack Overflow用户
提问于 2018-08-04 13:37:18
回答 1查看 3.9K关注 0票数 13

我想知道这是否有可能直接在Cython代码(即.pyx中)中迭代一个映射。以下是我的例子:

代码语言:javascript
复制
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的答案:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-04 14:03:36

映射迭代器没有元素firstsecond。相反,它有一个operator*,它返回一个pair引用。在C++中,您可以一次使用it->first来完成这一任务,但是这种语法在Cython中不起作用(而且在本例中,它还不够聪明,无法决定使用->而不是.本身)。

相反,您使用cython.operator.dereference

代码语言:javascript
复制
from cython.operator cimport dereference

# ...

print(dereference(it).first)

类似地,it++可以用cython.operator.postincrement来完成

票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51686143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档