is there a smarter/nicer way to trim a vector given a value I want to erase, something similar to what trim does for strings, e.g. from
0 0 0 1 2 3 56 0 2 4 0 0
to
1 2 3 56 0 2 4
I cannot find a trim-like function, is find/erase the best option?
Suppose we are working with a
std::vector<int> v;
We want to trim zeros, so
auto const is_not_zero = [](int i){ return i != 0; };
To find the first non-zero element and delete everything before it,
auto const first_non_zero = std::find_if(v.begin(), v.end(), is_not_zero);
v.erase(b.begin(), first_non_zero);
To find the last non-zero, do the same with reverse iterators:
auto const last_non_zero = std::find_if(v.rbegin(), v.rend(), is_not_zero);
v.erase(last_non_zero.base(), v.end());
(std::reverse_iterator::base
returns the underlying ordinary iterator from a reverse one).
In many cases, it's best to just not do anything with the vector and simply work with an iterator pair for the relevant range of elements. You could also use a span:
#include <gsl/span>
// ...
auto non_zeros = gsl::span(nonzeros_start_iter, nonzeros_end_iter);
and you can use this span like any standard library container. In C++20 you can switch gsl::span
to std::span
.
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