> > vector<int> data;
> > vector<bool> flags;
> > My objectives are:
> > 1) remove all elements from data where corressponding flag is true
> > 2) do it the STL way ;-)
> To be proper, you would need another structure and some simple things.
> I used the _Selects from g++, but they are available elsewhere.
> vector<pair<int, bool> > t;
> transform(data.begin(), data.end(), flags.begin(), back_inserter(t),
> make_pair<int, bool>);
> t.erase(remove_if(t.begin(), t.end(),
> _Select2nd<pair<int, bool> >()), t.end());
> data.resize(t.size());
> transform(t.begin(), t.end(), data.begin(),
> _Select1st<pair<int, bool> >());
> If you can use a special int value such as -1, you could do it in two
> steps.
> int selector (int i, bool b) {
> return b ? -1 : i;
> }
> transform(data.begin(), data.end(), flags.begin(), data.begin(),
> selector);
> data.erase(remove(data.begin(), data.end(), -1), data.end());
> If you prefer to violate the rules and use a predicate with
> side-effects,
> the following will do the job.
> template <class Iter, class T>
> struct Picker {
> Iter& it;
> Picker (Iter& it) : it(it) {
> }
> bool operator() (T const&) {
> return *it++;
> }
> };
> vector<bool>::const_iterator t(flags.begin());
> data.erase(remove_if(data.begin(), data.end(),
> Picker<vector<bool>::const_iterator, int>(t)), data.end());
> In any case, clear the flags.
> flags = vector<bool>(data.size());
Does transform require that the op function/functor have no side
effects, if not then using a a struct containing a reference to a vector
of ints and an operator () that push_back's the int arg to this vector,
if the bool is true, and returns anything say int.
// an output iterator to write to nowhere
template <class T>
struct null_iterator:public std::iterator<std::output_iterator_tag,
void,void,void,void>
{
null_iterator & operator = (const T &){return *this;}
null_iterator & operator * () {return *this;}
null_iterator & operator ++() {return *this;}
};
struct chooser
{
std::vector<int> &out;
explicit choooser(std::vector<int> &a):out(a){}
bool operator () (int x,bool y)
{
if(y) out.push_back(x);
return y;
}
}
...
void cleanup(std::vector<int> &data,std::vector<bool> &flags)
{
std::vector<int> out;
std::transform(data.begin(),data.end(),flags.end(),
null_iterator<bool>(),chooser(out));
data.swap(out);
flags = std::vector<bool>(data.size());
}
[ about comp.lang.c++.moderated. First time posters: do this! ]