有没有办法在 Cython 中导入 std::find find_if 等?

Wan*_*ang 1 c++ vector cython

是否可以导入 std::find,在那里libcpp.algorithm我只找到非常有限的功能。现在我必须循环遍历向量并进行比较。

Dav*_*idW 5

您只需遵循用于包装其他函数的方案libcpp.algorithm

cdef extern from "<algorithm>" namespace "std":
    Iter find_if[Iter, Func](Iter first, Iter last, Func pred)

from libcpp.vector cimport vector
from libcpp cimport bool

cdef bool findtwo(int a):
    if a==2:
        return True


def test():
    cdef vector[int] v = [1,2,3,4,2]
    cdef vector[int].iterator found = find_if(v.begin(), v.end(), findtwo)
    if found != v.end():
        print("Found")
Run Code Online (Sandbox Code Playgroud)

您会发现最大的限制在于您可以作为谓词函数传递的内容:它必须是一个cdef函数,这意味着没有 Python 闭包,没有可调用的 Python 对象等。还要注意,您返回的任何 Python 对象都将是解释为true(即不是 a nullptr),因此请务必返回 C++ bool,如我所示。