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
你应该在if语句中使用==
吗?
经典错误:-) - 比较需要两个等号
if (*a == *j)
if (*a = *j)
是一项任务
if (*a == *j)
You can just insert one set into another in one go:
std::set<int> s1, s2;
s1.insert(s2.begin(), s2.end());
Set members are unique, so there's nothing else to worry about.
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 =
?
#include <algorithm> ... std::set_union(s1.begin(), s1.end(), s2.begin(), s2.end() ... )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.