如何在Cython中迭代C集?

我用Cython优化 python代码. C中的一个集合存储了我的所有结果,我不知道如何访问数据以将其移动到 Python对象中.结构必须是一组.我无法将其更改为矢量,列表等.

我知道如何在Python和C中执行此操作,但不是在Cython中.如何在Cython中检索迭代器?我通过libcpp.STLContainer获取STL容器,如

from libcpp.vector cimport vector

但是,我不知道迭代器在Cython中是如何工作的.我需要导入什么?并且,使用迭代器的语法与它们在C中的工作方式相比是否有任何变化?

解决方法

Cython应该在需要时自动将c set转换为python set,但是如果你真的需要在c对象上使用迭代器,你也可以这样做.

如果我们做一个非常简单的例子,我们在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++"
     )))

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...