std::set 与自定义类型的区别
我已经定义了自己的结构
struct element {
int id;
float value;
}
,并将其与 std::set
一起使用。我想使用 set_difference
算法(就像上一个问题 用于确定两个集合的差异当我尝试调用代码时,编译停止并显示以下错误消息:
/usr/include/c++/4.2.1/bits/stl_algobase.h:268: error: passing
'const element' as 'this' argument of 'element& element::operator=(const element&)'
discards qualifiers
一个最小的示例可能如下所示:
std::set<struct element> s1;
std::set<struct element> s2;
std::set<struct element> s3;
element e1 = { 1, 11.0 };
element e2 = { 2, 22.0 };
element e3 = { 3, 33.0 };
s1.insert(e1);
s1.insert(e2);
s2.insert(e2);
s2.insert(e3);
set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), s3.begin());
I've defined my own struct like
struct element {
int id;
float value;
}
and I'm using it with std::set
. I want to use the set_difference
algorithm (like already mentioned in a previous question for determining the difference of two sets. When I try to invoke the code, compilation stops with the following error message:
/usr/include/c++/4.2.1/bits/stl_algobase.h:268: error: passing
'const element' as 'this' argument of 'element& element::operator=(const element&)'
discards qualifiers
A minimal example may look like this:
std::set<struct element> s1;
std::set<struct element> s2;
std::set<struct element> s3;
element e1 = { 1, 11.0 };
element e2 = { 2, 22.0 };
element e3 = { 3, 33.0 };
s1.insert(e1);
s1.insert(e2);
s2.insert(e2);
s2.insert(e3);
set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), s3.begin());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
示例: http://ideone.com/B4Cc1
通过放置
s3.begin()
作为输出迭代器,您意味着您想要用集合差异覆盖集合的前面区域。覆盖要求集合的大小大于结果,这在大多数情况下显然是不正确的;即使集合不为空,也不能使用 s3.begin() 作为输出,因为迭代器是只读的(否则会破坏排序顺序)。OTOH,
std::inserter(x, cit)
意味着,每当分配此输出迭代器 (*it = y
) 时,都会调用 insert 方法 (x.insert(cit, y)
),这就是您真正想要的:从空填充集合。Example: http://ideone.com/B4Cc1
By putting
s3.begin()
as the output iterator, you would mean that you want to overwrite the front region of the set with the set difference. Overwriting requires the size of set being larger than the result, which is obviously not true most of the time; even if the set is not empty, you can't uses3.begin()
as output because the iterator is read-only (otherwise it would destroy the sorted order).OTOH,
std::inserter(x, cit)
means that, whenever this output iterator is assigned (*it = y
), the insert method will be called (x.insert(cit, y)
), which is what you really want: populate a set from empty.