只读结构中的数据成员分配,STL集中的类 [英] Assignment of data-member in read-only structure, class in STL set

查看:149
本文介绍了只读结构中的数据成员分配,STL集中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题的最小示例转载如下:

  #include< set& 
using namespace std;

class foo {
public:
int value,x;
foo(const int& in_v){
value = in_v;
x = 0;
}
bool operator<(const foo& rhs)const {
return value< rhs.value;
}
};

int main(){
foo y(3);
set< foo> F;
F.insert(y);

//现在尝试修改集合的成员
F.begin() - > x = 1;
return 0;
}

错误错误: 'foo :: value'in read-only structure 。我觉得我在这里缺少一些简单的东西,但为什么我无法修改我的类中的 x 成员?

set 中的对象是不可变的;如果你想修改一个对象,你需要:


  1. / code>,

  2. 修改副本,

  3. 中删除​​原始对象

  4. 将副本插入 set

它看起来像这样:

  std :: set< int& s; 
s.insert(1);

int x = * s.begin(); //(1)
x + = 1; //(2)
s.erase(s.begin()); //(3)
s.insert(x); //(4)


The minimal example of the problem I'm having is reproduced below:

#include <set>
using namespace std;

class foo {
public:
  int value, x;
  foo(const int & in_v) {
   value = in_v;
   x = 0;
  }
  bool operator<(const foo & rhs) const {
   return value < rhs.value; 
 }
};

int main() {
  foo y(3);
  set<foo> F;
  F.insert(y);

  // Now try to modify a member of the set
  F.begin()->x=1;
  return 0;
}

With the error error: assignment of data-member ‘foo::value’ in read-only structure. I feel like I'm missing something simple here, but why am I unable to modify the member x in my class?

解决方案

Objects in a set are immutable; if you want to modify an object, you need to:

  1. make a copy of the object from the set,
  2. modify the copy,
  3. remove the original object from the set, and
  4. insert the copy into the set

It will look something like this:

std::set<int> s;
s.insert(1);

int x = *s.begin(); // (1)
x+= 1;              // (2)
s.erase(s.begin()); // (3)
s.insert(x);        // (4)

这篇关于只读结构中的数据成员分配,STL集中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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