modification the key in set
Class Employee {
public:
...
void setTitle(const string& title);
int idNumber() const;
...
};
struct IDNumberLess:
public binary_function<Employee, Employee, bool> {
bool operator()(const Employee& lhs, const Employee& rhs) const {
return lhs.idNuber() < rhs.idNumber();
}
};
typedef set<Employee, IDNumberLess> EmpIDSet;
EmpIDSet se;
Employee selectedID;
...
EmpIDSet::iterator i = se.find(selectedID);
if (i != se.end()) {
i->setTitile("Corporate Deity"); // some STL implementations reject
} // this line because *i is const
Solution ( two ways )
I. Cast
Note: casts are dangerous, and can’ t be used to change the key of map and mulitmap which contains elements of type pair (const K, V)
if (i != se.end()) {
const_cast<Employee&>(*i).setTitle("Corporate Deity");
}
doesn’t work
if (i != se.end()) {
static_cast<Employee>(*i).setTitle("Corporate Deity");
}
or
if (i != se.end()) {
((Employee)(*i)).setTitle("Corporate Deity");
}
above two are equivalent to this:
if (i != se.end()) {
Employee tmpCopy(*i);
tmpCopy.setTitle("Corporate Deity");
}
II. Erase and insert
if (i != se.end()) {
Employee e(*i);
e.setTitle("Corporate Deity");
se.erase(i++);
se.insert(i, e);
}