C++ 只读结构中数据成员的赋值,STL 集中的类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3775414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assignment of data-member in read-only structure, class in STL set
提问by Hooked
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?
随着错误error: assignment of data-member ‘foo::value' in read-only structure
。我觉得我在这里遗漏了一些简单的东西,但为什么我无法修改x
班级中的成员?
回答by James McNellis
Objects in a set
are immutable; if you want to modify an object, you need to:
aset
中的对象是不可变的;如果你想修改一个对象,你需要:
- 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
- 从
set
,复制对象 - 修改副本,
- 从 中删除原始对象
set
,并且 - 将副本插入
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)
回答by Craig
Given that the "x" variable is not involved in the less-than comparison, it would be safe in this case to make "x" mutable, allowing you to modify it from within the set. Your class definition would then become:
鉴于“x”变量不参与小于比较,在这种情况下使“x”可变是安全的,允许您从集合中修改它。您的类定义将变为:
class foo {
public:
int value;
mutable int x;
foo(const int & in_v) : value(in_v), x(0) { }
bool operator<(const foo & rhs) const {
return value < rhs.value;
}
};
And you can now use it in the std::set and modify x as you like. In this case it is pointless to keep two copies of the data structure as the previous poster has suggested.
您现在可以在 std::set 中使用它并根据需要修改 x 。在这种情况下,像前一个海报所建议的那样保留数据结构的两个副本是没有意义的。
回答by Arun
From the definition of the operator<
(i.e. considering only the value return value < rhs.value
and ignoring the x
), I am wondering whether you want a map
instead of a set
. In map
, the second
value ismutable.
从 the 的定义operator<
(即只考虑值return value < rhs.value
而忽略x
),我想知道您是否想要 amap
而不是 a set
。在 中map
,该second
值是可变的。