I have an std::vector
of std::strings
containing data similar to this:
[0] = ""
[1] = "Abc"
[2] = "Def"
[3] = ""
[4] = "Ghi"
[5] = ""
[6] = ""
How can I get a vector containing the 4 strings from 1 to 4? (i.e. I want to trim all blank strings from the start and end of the vector):
[0] = "Abc"
[1] = "Def"
[2] = ""
[3] = "Ghi"
Currently, I am using a forward iterator to make my way up to "Abc"
and a reverse iterator to make my way back to "Ghi"
, and then constructing a new vector using those iterators. This method works, but I want to know if there is an easier way to trim these elements.
P.S. I'm a C++ noob.
Also, I should mention that the vector may be composed entirely of blank strings, in which case a 0-sized vector would be the desired result.
How about this, with a predicate:
class StringNotEmpty
{
bool operator()(const std::string& s) { return !s.empty(); }
};
Now to trim:
vec.erase(std::find_if(vec.rbegin(), vec.rend(), StringNotEmpty()).base(), vec.end());
vec.erase(vec.begin(), std::find_if(vec.begin(), vec.end(), StringNotEmpty()));
There might be an off-by-one on the .base()
call, but the general idea should work.
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