在编写自定义谓词函数/函子以传递给 STL 算法时,是否允许谓词使用其参数的地址?
这是激发问题的问题。我有一个向量vec
和一个向量inds
,其中包含一些索引vec
。我想删除那些vec
索引在inds
.
一种方法是使用remove_if
谓词函子,该函子通过获取其地址InInds
来确定其参数的索引:vec
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
如果直接在vec
. 如果在元素的副本上调用它会中断,因为副本的地址对于确定element
的索引没有用处。
我的问题是:这个谓词是否适用于remove_if
任何符合标准的编译器?或者谓词是否严格意味着只对值而不是地址进行操作?