我有一个 std::set<Foo>
,我想要更新其中一个现有元素的某个值。请注意,我更新的这个值不会改变集合中元素的顺序。
#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;
}
有没有简洁的方法来做这个?还是我必须检查元素是否已经存在,如果存在,则删除它,添加值并重新插入?
insert()
返回的pair
的第二个成员具有相反的含义。当插入实际发生时,它是true
,而当元素已经存在时,它是false
。 - Alex Che