我有一个 std::set
,我想更新一些值其中存在的元素.请注意,我正在更新的值不会更改集合中的顺序:
I have a std::set<Foo>
, and I'd like to update some value of
an existing element therein. Note that the value I'm updating does not change the order in the set:
#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;
}
有什么简洁的方法可以做到这一点吗?或者我是否必须检查该元素是否已经存在,如果存在,将其删除,添加值并重新插入?
Is there any concise way to do this? Or do I have to check if the element is already there, and if so, remove it, add the value and re-insert?
由于 val
不参与比较,可以声明为 mutable
Since val
is not involved in comparison, it could be declared mutable
struct Foo {
Foo(int i, int j) : id(i), val(j) {}
int id;
mutable int val;
bool operator<(const Foo& other) const {
return id < other.id;
}
};
这意味着 val
的值可能会在逻辑常量 Foo 中发生变化,这意味着它不应该影响其他比较运算符等.
This implies that the value of val
may change in a logically-const Foo, which means that it shouldn't affect other comparison operators etc.
或者您可以直接删除和插入,如果插入使用旧位置就在之后的位置作为提示,则需要O(1)额外的时间(与访问和修改相比).
Or you could just remove and insert, that takes O(1) additional time (compared to accessing and modifying) if insertion uses the position just before just after the old one as the hint.
类似于:
bool alreadyThere = !p.second; // you forgot the !
if (alreadyThere)
{
Set::iterator hint = p.first;
hint++;
s.erase(p.first);
s.insert(hint, f);
}
这篇关于如何更新 std::set 的现有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!