How to update an existing element of std::set?(如何更新 std::set 的现有元素?)
问题描述
我有一个 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 的现有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何更新 std::set 的现有元素?
 
				
         
 
            
        基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				