在PythonList上使用C++迭代器和Python/capi?

2024-06-11 22:46:27 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以只使用IteratorsPyObjects上模块<algorithm>的函数指针?在

我要解决的具体问题(它的构建是为了向它学习):

  • 我在python列表中存储了大量id
  • 现在,我想用C++中的模块< ^ /LI>在这个列表上执行一个^ {CD4}}

一种方法可以是以c-array的形式访问python列表,从中构造一个向量(它使用指针/不复制),执行二进制搜索并将数组导出为PyObject。在

有可能吗?在


Tags: 模块方法id列表二进制liarray向量
1条回答
网友
1楼 · 发布于 2024-06-11 22:46:27

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

如果您真的想使用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()。在

相关问题 更多 >