Board index » cppbuilder » STL, reverse_iterator and erase

STL, reverse_iterator and erase


2006-04-12 04:20:39 PM
cppbuilder66
Hi All,
please help me with this example:
vector<string>ProgText;
//remove empty strings from the begining
for(string *str = ProgText.begin(); str < ProgText.end(); )
if(str->empty()) str = ProgText.erase(str);
else break;
this works !
//remove empty strings from the end
for(reverse_iterator<string*>str = ProgText.rbegin(); str <
ProgText.rend(); )
if(str->empty()) str = ProgText.erase(str);
here comes compiler mistake
[C++ Error] Experiment.cpp(426): E2285 Could not find a match for
'vector<string,allocator<string>>::erase(reverse_iterator<string *>)'
else break;
how to erase strings from the end correctly ?
THANX!
Boris
 
 

Re:STL, reverse_iterator and erase

Boris Epel < XXXX@XXXXX.COM >writes:
Quote
vector<string>ProgText;
This won't compile since vector and string aren't declared.
Please next time post a minimal snippet (i.e. not too big, but not too
small, either); thanks!
Quote
//remove empty strings from the begining
for(string *str = ProgText.begin(); str < ProgText.end(); )
This relies on the return value of ProgText.begin() being implicitly
convertible to string *. The return value may be convertible to string
*, but it is not required to be. Better write
typedef std::vector<std::string>ProgText ProgText_type;
ProgText_type ProgText;
and later
for (ProgText_type::iterator str = ProgText.begin(); str != ProgText.end(); )
(or ProgText_type::const_iterator, if ProgText is const).
Note that I have also changed the comparison operator from < to
!=. This isn't strictly necessary as long as we deal with std::vector,
but it is a good practice to use !=, which is supported by much more
iterator types than <.
Quote
if(str->empty()) str = ProgText.erase(str);
else break;
this works !

//remove empty strings from the end
for(reverse_iterator<string*>str = ProgText.rbegin(); str <
ProgText.rend(); )
The type of ProgText.rbegin() and ProgText.rend() is not
reverse_iterator<string*>, but ProgText_type::reverse_iterator (or
ProgText_type::const_reverse_iterator, if ProgText is const).