简体   繁体   中英

cython - how to iterate over c++ list

I want to initiate a cpp list in cython, assign values to it and then iterate over the list to obtain its values. A generic code could look like this:

from libcpp.list cimport list as cpplist
from cpython cimport array
import array

cdef int[:] c_volumecheck(int n, int comb):

    cdef:
        array.array match = array.array('i', [0]*(n*comb))        
        int[:] match_c = match
        cpplist[int] arr
    
    asign(match_c, comb, n, arr)

    return match_c


cdef void asign(int[:] match, int row, int col, cpplist[int] arr):

    cdef int j, i

    for j in range(row):
        for i in range(col):
            arr.push_back(1)

    for j in range(row):
        for i in range(col):
            match[j*col + i] = arr[j*col +i]

However, when I compile this I get the error:

Indexing list[int] not supported for index type int

Given the way they iterate over cpp vectors here I thought that would be the way to go.

C++ std::list s are doubly linked lists (ie each element has a pointer to the next and previous one) which makes adding/inserting elements efficient, but means that indexing isn't supported in either Cython or in C++. Instead you should use the iterator protocol:

# at top of file
from cython.operator import dereference, preincrement

# in function
cdef cpplist[int].iterator it

it = arr.begin()

for j in range(row):
    for i in range(col):
        match[j*col + i] = dereference(it)
        preincrement(it)

This is (close to) how you'd do the iteration in C++ too.

In the more general case you'd want to compare the iterator against arr.end() to see when you've reached the end of the list. Since you should know the length here I haven't do so.

The int in python is not bounded to the system-bus-size, lists in C++ are using another int as indexing, an int with maximum of 32/64 bits capacity. ctypes.c_int should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM