[英]How to iterate throught C++ sets in Cython?
我用Cython優化python代碼。 C ++中的一個集合存儲了我的所有結果,我不知道如何訪問數據以將其移動到Python對象中。 結構必須是一組。 我無法將其更改為矢量,列表等。
我知道如何在Python和C ++中這樣做,但不是在Cython中。 如何在Cython中檢索迭代器? 我通過libcpp.STLContainer獲取STL容器,如
來自libcpp.vector cimport vector
但是,我不知道迭代器在Cython中是如何工作的。 我需要導入什么? 並且,與使用C ++的方式相比,使用迭代器的語法是否有任何變化?
用Cython應自動轉換為C需要的時候++設置為蟒蛇集,但是如果你確實需要使用在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 ++映射到python dict。 這是我對地圖案例的粗略的cython代碼:
from libcpp.map cimport map
# code here for _make_map() etc.
def get_map():
'''
get_map()
Example of cython interacting with C++ map.
:returns: Converts C++ map<int, int> to python dict and returns the dict
:rtype: dict
'''
cdef map[int, int] cpp_map = _make_map()
pymap = {}
for it in cpp_map: #Iterate through the c++ map
pymap[it.first] = it.second
return pymap
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.