Como atualizar um elemento existente do std :: set?
Eu tenho umstd::set<Foo>
e gostaria de atualizar algum valor de um elemento existente. Observe que o valor que estou atualizando não altera a ordem no 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;
}
Existe alguma maneira concisa de fazer isso? Ou tenho que verificar se o elemento já está lá e, se estiver, remova-o, adicione o valor e insira-o novamente