Re: remove_if with a mask
On 6/8/2010 10:16 AM, eLVa wrote:
On 8 juin, 10:09, "Leigh Johnston"<le...@i42.co.uk> wrote:
"Victor Bazarov"<v.baza...@comcast.invalid> wrote in message
news:hulh6q$46f$1@news.eternal-september.org...
On 6/8/2010 9:13 AM, eLVa wrote:
I have a simple problem : you are given a container, let's say a
vector of some objects, and a vector of bool which is to be treated as
a mask. You have to remove every element from the container for which
the mask is true.
basically, two iterators (one over the container and one over the
mask) iterates through their respective containers, removing elements
from the first when the second is true. I tried a few solutions, using
remove_if but I was not succesful !
Post what you have, post what didn't work, post your explanation on how
you expected it to work. Otherwise this looks too much like homework, and
we don't do homework.
Ok ! Wait a minute there, it's not an homework, it's a question I'm
trying to resolve.
Sure, I trust your word. Not a homework. Absolutely. And if you
*were* a student, you would definitely admit that it's homework, yes?
That's settled, then.
I thought that it was not wise to keep an iterator into a functor used
in remove_if.
I am not sure how to respond when somebody says that something "isn't
wise". You must be wiser than I am... It's probably wise for you not
to use my advice then. :-)
> I wanted a direction, that's all.
OK. Did you get it? If you did, happy for you. If you didn't, sorry.
Better luck next time.
So that's what I got :
template<class Z> struct maskChecker {
public:
maskChecker(const vector<bool> &mask) : it(mask.begin()) {}
bool operator()(Z&) const { return *it ++; }
private:
mutable vector<bool>::const_iterator it;
Instead of keeping a mutable iterator by value, I'd probably keep a
reference to an iterator. But, yes, that's the general idea.
};
template<class T> template<class Z>
void Selector<T>::compact(vector<Z> &data, const vector<bool> &mask) {
if (data.size() != mask.size()) throw UnmatchedSize(data.size(),
mask.size());
typename vector<Z>::iterator end = remove_if(data.begin(),
data.end(), maskChecker<Z>(mask));
data.erase(end, data.end());
}
That's kinda working, what's your opinion ?
I would do almost exactly the same, except for the iterator (I just
don't like 'mutable' for some reason). If it works, then you're OK, I
think.
[lib.alg.remove/5] says that the complexity is *exactly* (last-first)
applications of the corresponding predicate. If you had a reference to
the mask iterator, you could compare the iterator to mask.end() after
the call to 'remove_if' as well (and even assert on that).
[..]
Since you weren't really replying to my post, I only can answer *my*
questions and continue discussion on the points *I* raised.
V
--
I do not respond to top-posted replies, please don't ask