std::set 与自定义类型的区别

发布于 2024-12-20 19:18:01 字数 954 浏览 3 评论 0原文

我已经定义了自己的结构

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浪推晚风 2024-12-27 19:18:01
set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
               std::inserter(s3, s3.begin()));
//             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

示例: http://ideone.com/B4Cc1

通过放置 s3.begin()作为输出迭代器,您意味着您想要用集合差异覆盖集合的前面区域。覆盖要求集合的大小大于结果,这在大多数情况下显然是不正确的;即使集合不为空,也不能使用 s3.begin() 作为输出,因为迭代器是只读的(否则会破坏排序顺序)。

OTOH,std::inserter(x, cit) 意味着,每当分配此输出迭代器 (*it = y) 时,都会调用 insert 方法 (x.insert(cit, y)),这就是您真正想要的:从空填充集合。

set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
               std::inserter(s3, s3.begin()));
//             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

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 use s3.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文