I have written a function in cython that will search a STL vector of strings for a given string and return true if it is found, false otherwise. Performance is very important here! I would ideally like to have a templated function to do the same thing so I don't have to write a function for each data type. I am sure this is possible but I don't know the cython syntax for templated functions. (I know how to do it in 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
Can anyone give me a hand?
Use Fused Types.
Example:
cimport cython
ctypedef fused any:
string
cython.int
cpdef bool is_in_vector(string a, vector[any] v)
Or this way:
ctypedef fused vector_t:
vector[string]
vector[cython.int]
cpdef bool is_in_vector(string a, vector_t v)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With