只读结构中的数据成员分配,STL集中的类 [英] Assignment of data-member in read-only structure, class in STL set
本文介绍了只读结构中的数据成员分配,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
中的对象是不可变的;如果你想修改一个对象,你需要:
- 从
/ code>,
- 修改副本,
- 从
中删除原始对象
和 - 将副本插入
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:
- make a copy of the object from the
set
, - modify the copy,
- remove the original object from the
set
, and - 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屋!
查看全文