STL迭代器不起作用?不明白为什么
我有一个类,它有一个私有成员:
std::set<unsigned long> Sset;
我对这个函数有一个问题:
原型:
Set& Union (Set&, Set&);
代码:
Set& Set::Union (Set& s1, Set& s2)
{
set<unsigned long>::iterator a;
set<unsigned long>::iterator j;
for (a = s1.Sset.begin(); a!=s1.Sset.end(); ++a)
for (j = s2.Sset.begin(); j!=s2.Sset.end(); ++j)
if (*a = *j)
{
Sset.insert(*a);
break;
}
return *this;
}
我得到编译器错误 表达式必须是可修改的左值 *a=*j
一切正常迭代器 j,但它不接受 *a
有任何帮助或解释吗? 谢谢
I have a class which has one private member:
std::set<unsigned long> Sset;
And I have a problem with this function:
Prototype:
Set& Union (Set&, Set&);
Code:
Set& Set::Union (Set& s1, Set& s2)
{
set<unsigned long>::iterator a;
set<unsigned long>::iterator j;
for (a = s1.Sset.begin(); a!=s1.Sset.end(); ++a)
for (j = s2.Sset.begin(); j!=s2.Sset.end(); ++j)
if (*a = *j)
{
Sset.insert(*a);
break;
}
return *this;
}
I get compiler error expression must be a modifiable lvalue at *a=*j
Everything is OK with iterator j, but it won't accept *a
Any help, or explanation?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您应该在 if 语句中使用
==
吗?should you be using
==
in the if statement?经典错误:-) - 比较需要两个等号
Classic mistakes :-) - comparison requires two equals signs
是一个作业
is an assignment
您可以一次性将一个集合插入另一个集合:
集合成员是唯一的,因此无需担心其他问题。
You can just insert one set into another in one go:
Set members are unique, so there's nothing else to worry about.
您无法分配给
set::iterator
指向的值。为什么?
因为集合按照任何感觉的顺序保留其元素(
集合
,具体来说,是排序的)以允许快速检索,所以您可以'不必手动告诉它在哪里放置元素。相反,将元素
插入
到正确的位置。话虽如此,您的意思是使用
==
而不是=
吗?You can't assign to the value pointed to by a
set::iterator
.Why?
Because sets keep their elements in whatever order it feels like (
set
, specifically, is sorted) to allow for quick retrieval, so you can't manually tell it where to put elements.Instead,
insert
the element at the right place.Having said that -- did you mean to use
==
instead of=
?http://en.cppreference.com/w/cpp/algorithm/set_union
http://en.cppreference.com/w/cpp/algorithm/set_union