【发布时间】:2011-11-12 12:23:41
【问题描述】:
我有一个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()返回的对中的second成员具有相反的含义。当插入实际发生时是true,当元素已经存在时是false。