When writing a custom predicate function/functor to pass to an STL algorithm, is the predicate allowed to use the address of its argument?
Here's the problem that inspired the question. I have a vector vec
, and a vector inds
, which contains some indices into vec
. I'd like to remove those elements in vec
whose indices are listed in inds
.
One approach is to use remove_if
with a predicate functor InInds
that determines its argument's index in vec
by taking its address:
class InInds {
private:
const vector<Element>& vec_;
const vector<int>& inds_;
public:
InInds(const vector<Element>& vec, const vector<int>& inds)
: vec_(vec), inds_(inds) {}
bool operator()(const Element& element) {
// WARNING: uses the ADDRESS of element, not its value. May not be kosher?
int index = &element - &vec[0];
return std::find(inds_.begin(), inds_.end(), index) != inds_.end();
}
}
InInds
works if called directly on an element in vec
. It will break if it's called on a copy of an element, since the copy's address will not be useful to determine element
's index.
My question is: will this predicate work in remove_if
for any standards-compliant compiler? Or are predicates strictly meant to operate only on values, not addresses?