Arguably, push_back
(and so also +=
) is rather inefficient as it run in a Python loop. To be sure, initializing std::vector
from a numpy array isn’t terribly better unless that array is 1D, but if you start out from an empty vector, it’s better to use swap()
. You can copy the one you’re taking the contents from if need be. Examples:
import cppyy
import numpy as np
vec = cppyy.gbl.std.vector['unsigned int']
val = 2**32-1
a = np.array([val], dtype=np.uint32)
assert a[0] == val
v1 = vec(a)
assert v1[0] == val
v2 = vec()
v2.swap(vec(a))
assert v2[0] == val
v3 = vec()
v3.swap(vec(v1))
assert v1[0] == val
assert v3[0] == val