From Cython I'm using C++'s std:vector
and I need to remove an element. For my exact use case all of the vectors are of type int
. I thought that the cleanest way to do this would be to use std:remove
and vector's erase
method. For some reason the following code is not removing the elements as expected:
# distutils: language=c++
from libcpp.vector cimport vector
cdef extern from "<algorithm>" namespace "std":
iter std_remove "std::remove" [iter, T](iter first, iter last, const T& val)
cdef void remove(vector[int] vect, int elem):
vect.erase(std_remove[vector[int].iterator, int](vect.begin(), vect.end(), elem))
def blah():
cdef vector[int] vect
cdef int i
for i in range(10):
vect.push_back(i)
for i in range(10):
print vect[i]
remove(vect, i)
return vect
When I run print blah()
I see:
0
1
...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In other words the elements are not being removed from the vector. What simple mistake am I making?
Removing an element from a vector in C++ is extremely easy. Your erase/remove combo is for more complicated stuff.
Given an iterator
it
, thenwill erase it (see the pertinent
vector
doc).Incidentally, if you need to find this iterator, you can use
find
(fromalgorithm
):Consequently, to erase the first occurrence of
value
, you can useP.S. This isn't really a Cython question at all. It's a C++ question which came up in the context of Cython. Please consider retagging. This will help you get attention for your question from relevant people.