是否可以使用只需要 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()
。