Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming a vector of strings

Tags:

c++

string

vector

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.

Edit

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.

like image 844
dreamlax Avatar asked Jan 09 '11 22:01

dreamlax


1 Answers

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.

like image 144
ltjax Avatar answered Oct 09 '22 16:10

ltjax