我用Cython优化
python代码. C中的一个集合存储了我的所有结果,我不知道如何访问数据以将其移动到
Python对象中.结构必须是一组.我无法将其更改为矢量,列表等.
我知道如何在Python和C中执行此操作,但不是在Cython中.如何在Cython中检索迭代器?我通过libcpp.STLContainer获取STL容器,如
from libcpp.vector cimport vector
但是,我不知道迭代器在Cython中是如何工作的.我需要导入什么?并且,使用迭代器的语法与它们在C中的工作方式相比是否有任何变化?
解决方法
Cython应该在需要时自动将c set转换为python set,但是如果你真的需要在c对象上使用迭代器,你也可以这样做.
libset.cc
#include <set> std::set<int> make_set() { return {1,2,3,4}; }
libset.h
#include <set> std::set<int> make_set();
然后我们可以为这段代码编写cython包装器,其中我给出了一个如何以一种漂亮的pythonic方式(在后台使用c迭代器)迭代集合的示例以及如何直接执行它的示例用迭代器.
pyset.pyx
from libcpp.set cimport set from cython.operator cimport dereference as deref,preincrement as inc cdef extern from "libset.h": cdef set[int] _make_set "make_set"() def make_set(): cdef set[int] cpp_set = _make_set() for i in cpp_set: #Iterate through the set as a c++ set print i #Iterate through the set using c++ iterators. cdef set[int].iterator it = cpp_set.begin() while it != cpp_set.end(): print deref(it) inc(it) return cpp_set #Automatically convert the c++ set into a python set
然后可以使用简单的setup.py编译它
setup.py
from distutils.core import setup,Extension from Cython.Build import cythonize setup( ext_modules = cythonize(Extension( "pyset",sources=["pyset.pyx","libset.cc"],extra_compile_args=["-std=c++11"],language="c++" )))
原文地址:https://www.jb51.cc/c/114279.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。