¿Cómo actualizar un elemento existente de std :: set?
Tengo unstd::set<Foo>
, y me gustaría actualizar algún valor de un elemento existente en el mismo. Tenga en cuenta que el valor que estoy actualizando no cambia el orden en el conjunto:
#include <iostream>
#include <set>
#include <utility>
struct Foo {
Foo(int i, int j) : id(i), val(j) {}
int id;
int val;
bool operator<(const Foo& other) const {
return id < other.id;
}
};
typedef std::set<Foo> Set;
void update(Set& s, Foo f) {
std::pair<Set::iterator, bool> p = s.insert(f);
bool alreadyThere = p.second;
if (alreadyThere)
p.first->val += f.val; // error: assignment of data-member
// ‘Foo::val’ in read-only structure
}
int main(int argc, char** argv){
Set s;
update(s, Foo(1, 10));
update(s, Foo(1, 5));
// Now there should be one Foo object with val==15 in the set.
return 0;
}
¿Hay alguna forma concisa de hacer esto? ¿O tengo que verificar si el elemento ya está allí, y si es así, eliminarlo, agregar el valor y volver a insertarlo?