如何更改集合中的对象子成员
我正在使用一套来容纳物体。我想更改集合中的第一个对象。这是我尝试过的:
set<myClass>::iterator i = classlist.begin();
i->value = 0;
这是我得到的错误:
error: read-only variable is not assignable
变量如何变为只读?怎样才能改变呢?
I am using a set to hold objects. I want to make changes to the first object in the set. This is what I tried:
set<myClass>::iterator i = classlist.begin();
i->value = 0;
This is the error I get:
error: read-only variable is not assignable
How did the variable become read-only? How can it be changed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
集合中的内容实际上是只读的 - 您无法就地更改集合成员的值。您所能做的就是删除它,然后添加具有所需新值的新成员。由于 std::set 的二叉树实现,此限制是必要的。
The things in a set are effectively read-only - you cannot change the value of a member of a set in situ. All you can do is remove it, and add a new member with the required new value. This restriction is necessary because of the binary tree implementation of std::set.
如果您确实必须修改
set
中的元素,则该元素必须是一旦从
集合
中删除并重新插入到该集合
中。例如:
如果
myClass
的operator<
不引用value
成员,您可以使用
std::map
而不是set
。假设一个新的
myClass
没有value
成员,并假设
value
成员的类型为T
,然后 std::map< newMyClass,T>就可以达到目的了。
If you really have to modify the element in
set
, the element has to beonce erased from the
set
and re-inserted in thatset
.For example:
If
operator<
formyClass
doesn't refer thevalue
member,you can use
std::map
instead ofset
.Assuming a new
myClass
which doesn't havevalue
member,and assuming that the type of
value
member isT
,then
std::map< newMyClass, T >
will meet the purpose.这在 VS2008 下编译:
但这只是巧合。
operator<
比较comp
成员,然后我们更改value
成员。This compiles under VS2008:
But this only works by coincidence.
operator<
compares thecomp
members and we change thevalue
member.在 Visual Studio 2010 中,当 Microsoft 更新 STL 时,他们使所有迭代器保持不变。所以 set::iterator 和 set::const_iterator 是相同的。
原因是因为在一个集合中,关键是数据本身,当你改变你的数据时,也就改变了关键,这是不可以的。
微软 C++ 团队在此处报告了这一重大变化:
http://blogs.msdn.com/b/vcblog/archive/2009/05/25/stl-writing-changes-in-visual-studio-2010-beta-1.aspx
如果您想要修改数据,并且不想删除和插入数据,那么可以使用地图。
in Visual Studio 2010 when Microsoft updated the STL, they made all iterators constant. So set::iterator and set::const_iterator are the same.
The reason is because in a set, the key is the data itself, and when you change your data, and thus the key, which is a no no.
The microsoft C++ team reported on this breaking change here:
http://blogs.msdn.com/b/vcblog/archive/2009/05/25/stl-breaking-changes-in-visual-studio-2010-beta-1.aspx
If you want to be modifying your data, and don't want to be removing and inserting, then use a map instead.