如何更新std :: set的现有元素? [英] How to update an existing element of std::set?

查看:109
本文介绍了如何更新std :: set的现有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 std :: set< Foo> ,我想更新其中已有元素的
值。请注意,我要更新的值不会更改集合中的顺序:

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 不参与比较,因此可以将其声明为可变

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的现有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆