模板化STL容器作为cython中的函数参数

ibe*_*ell 5 python cython

我在cython中编写了一个函数,它将搜索给定字符串的字符串的STL向量,如果找到则返回true,否则返回false.性能在这里非常重要!理想情况下,我希望有一个模板化的函数来做同样的事情,所以我不必为每种数据类型编写函数.我确信这是可能的,但我不知道模板化函数的cython语法.(我知道如何在c ++中完成)

from libcpp cimport bool
from libcpp.string cimport string
from libcpp.vector cimport vector
from cython.operator cimport dereference as deref, preincrement as inc

cpdef bool is_in_vector(string a, vector[string] v):
    cdef vector[string].iterator it = v.begin()
    while it != v.end():
        if deref(it) == a:
            return True
        #Increment iterator
        inc(it)
    return False
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我一把吗?

Cza*_*zak 2

使用融合类型

例子:

cimport cython

ctypedef fused any:
    string
    cython.int

cpdef bool is_in_vector(string a, vector[any] v)
Run Code Online (Sandbox Code Playgroud)

或者这样:

ctypedef fused vector_t:
    vector[string]
    vector[cython.int]

cpdef bool is_in_vector(string a, vector_t v)
Run Code Online (Sandbox Code Playgroud)