I have a vector v1
, and a boolean vector v2
of the same size. I want to delete from v1
all values such that the parallel element of v2
is false
:
vector<int> v3; // assume v1 is vector<int> for (size_t i=0; i<v1.size(); i++) if (v2[i]) v3.push_back(v1[i]); v1=v3;
Is there a better way to do it?
Element access: reference operator [g] – Returns a reference to the element at position 'g' in the vector. at(g) – Returns a reference to the element at position 'g' in the vector. front() – Returns a reference to the first element in the vector. back() – Returns a reference to the last element in the vector.
Vectors are basic objects in R and they can be subsetted using the [ operator. The [ operator can be used to extract multiple elements of a vector by passing the operator an integer sequence.
vector::erase() erase() function is used to remove elements from a container from the specified position or range.
size_t last = 0; for (size_t i = 0; i < v1.size(); i++) { if (v2[i]) { v1[last++] = v1[i]; } } v1.erase(v1.begin() + last, v1.end());
Same as yours essentially, except it works in-place, not requiring additional storage. This is basically a reimplementation of std::remove_if
(which would be difficult to use directly, because the function object it uses is given a value, not an index or iterator into the container).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With