Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to trim a vector from custom values

Tags:

c++

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?

like image 647
cpl Avatar asked May 06 '19 12:05

cpl


2 Answers

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).

like image 84
lisyarus Avatar answered Oct 20 '22 16:10

lisyarus


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.

like image 39
einpoklum Avatar answered Oct 20 '22 14:10

einpoklum