2024-06-11 22:46:27 发布
网友
是否可以只使用Iterators和PyObjects上模块<algorithm>的函数指针?在
Iterators
PyObjects
<algorithm>
我要解决的具体问题(它的构建是为了向它学习):
一种方法可以是以c-array的形式访问python列表,从中构造一个向量(它使用指针/不复制),执行二进制搜索并将数组导出为PyObject。在
PyObject
有可能吗?在
好吧,二进制搜索并没有那么复杂,那么为什么不简单地基于一系列索引而不是迭代器来编写一个呢?我相信列表符合Python的sequence protocol,所以这应该很容易。在
如果您真的想使用binary_search()算法进行学习,还可以在Python序列之上创建STL风格的迭代器。您只需要一个指向序列的指针和一个创建随机访问迭代器的索引。如果愿意,还可以透明地将列表中的Python对象转换为相应的ID类型(我猜是整数类型)。在
binary_search()
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()。在
好吧,二进制搜索并没有那么复杂,那么为什么不简单地基于一系列索引而不是迭代器来编写一个呢?我相信列表符合Python的sequence protocol,所以这应该很容易。在
如果您真的想使用
binary_search()
算法进行学习,还可以在Python序列之上创建STL风格的迭代器。您只需要一个指向序列的指针和一个创建随机访问迭代器的索引。如果愿意,还可以透明地将列表中的Python对象转换为相应的ID类型(我猜是整数类型)。在我还没有编译这个,可能忘了几个部分,但我想你明白了。只需初始化两个迭代器,一个偏移量为零,另一个偏移量为容器大小,并将它们赋给
binary_search()
。在相关问题 更多 >
编程相关推荐