我发现更新操作std::set很繁琐,因为cppreference上没有这样的API .所以我现在做的是这样的:
//find element in set by iterator
Element copy = *iterator;
... // update member value on copy, varies
Set.erase(iterator);
Set.insert(copy);
Run Code Online (Sandbox Code Playgroud)
基本上迭代器返回的Set是a const_iterator,你不能直接改变它的值.
有一个更好的方法吗?或者也许我应该std::set通过创建我自己的(我不知道它是如何工作的...)来覆盖.
我有一个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)); …Run Code Online (Sandbox Code Playgroud)