c++ - 使用 Python/C API 在 Python-List 上使用 C++-Iterators?

标签 c++ python iterator python-c-api stl-algorithm

<分区>

是否可以使用只需要 Iterators 的工具?和来自模块 <algorithm> 的函数指针在 PyObjects

我要解决的具体问题(构造来借鉴):

  • 我在 python 列表中存储了大量 ID
  • 现在我想执行一个 std::binary_search在此列表中,使用用 C++ 编写的模块

一种方法是将 python 列表作为 c 数组访问,从中构造一个 vector (使用指针/不复制),执行 binary_search 并将数组导出为 PyObject .

这可能吗?

最佳答案

好吧,二分搜索并没有那么复杂,那么为什么不简单地根据一系列索引而不是迭代器来编写代码呢?我相信列表符合 sequence protocol Python,所以这应该很容易。

如果您真的想使用 binary_search() 算法进行学习,也可以在 Python 序列之上创建 STL 样式的迭代器。您所需要的只是一个指向序列的指针和一个用于创建随机访问迭代器的索引。如果需要,您还可以透明地将列表中的 Python 对象转换为相应的 ID 类型(我猜是某种整数类型)。

struct iterator
{
    // typedefs required for fully compliant STL-style iterators
    typedef PyObject* value_type;

    iterator(PyObject* seqeunce, Py_ssize_t position):
        m_sequence(sequence), m_position(position)
    {
        assert(PySequence_Check(m_sequence));
        assert(m_position >= 0);
        assert(m_position <= PySequence_GetSize(m_sequence));
    }
    value_type operator*() const
    {
        assert(m_position < PySequence_GetSize(m_sequence));
        return PySequence_GetItem(m_sequence, m_position);
    }
    iterator& operator++()
    {
        assert(m_position <= PySequence_GetSize(m_sequence));
        ++m_position;
        return *this;
    }
    iterator& operator+=(size_t l)
    {
        m_position += l;
        return *this;
    }
};

我还没有编译这个,可能忘记了一些部分,但我想你明白了。只需初始化两个迭代器,一个偏移量为零,另一个偏移量为容器大小,并将它们提供给 binary_search()

关于c++ - 使用 Python/C API 在 Python-List 上使用 C++-Iterators?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374490/

相关文章:

c++ - regex_match 不产生任何结果

c++ - 如何在构造函数中初始化 char 数组样式的字符串

python - 将 Twitter 时间转换为特定格式的日期时间,以统计一天中推文的频率

python - 理解 zip 函数

python - 如何将此代码从 Python 2.7 转换为 Python 3.5 以修复 ---> AttributeError : '_io.TextIOWrapper' object has no attribute 'next'

c++ - 为什么 std::max_element 需要 ForwardIterator?

c++ - SendInput()鼠标移动计算?

c++ - 调用指向已释放对象方法的 std::function 对象

python 语言环境无法在我的机器上运行 (osx 10.7.4)

android - 在 Android 上将应用程序数据保存在 kivy 中