set_intersection使用自定义设置比较器
set_intersection with a custom set comparator
当我将 std::set_intersection 函数与具有自定义比较器的集合一起使用时,我没有得到预期的结果。 以下代码输出 {5,9,7} 相交{9}为空集。但是,如果我只使用普通比较器,我会{9}。
#include <iostream>
#include <cstdlib>
#include <set>
using namespace std;
auto cmp = [](int* a, int* b) { return a < b; };
using stupid_set = set<int*, decltype(cmp)>;
int main() {
int* n5 = new int(5);
int* n9 = new int(9);
int* n7 = new int(7);
stupid_set s0 {n5, n9, n7};
stupid_set s1 {n9};
stupid_set i;
for (auto s:s0) {
cout << "s0:" << *s << endl;
}
for (auto s:s1) {
cout << "s1:" << *s << endl;
}
set_intersection(s0.begin(), s0.end(), s1.begin(), s1.end(), std::inserter(i, i.begin()));
for (auto x : i) {
cout << "Int=" << *x << endl;
}
}
您的代码存在多个问题,但核心问题是您对集合使用自定义比较器,而不是std::set_intersection
函数调用。此功能还需要比较元素,当然,必须将它们与同一比较器进行比较。
用:
struct cmp
{
bool operator()(int* a, int* b) const { return *a < *b; };
};
using stupid_set = set<int*, cmp>;
和
set_intersection(
s0.begin(), s0.end(),
s1.begin(), s1.end(),
std::inserter(i, i.begin()),
cmp{} // custom comparator used for sets
);
整个现场演示在这里:https://godbolt.org/z/OAr3xV。
请注意,如果省略比较器,std::set_intersection
将对 set 元素使用operator<
,并且此操作通常未定义指针。
如果你真的想比较指针而不是那里指向的整数值,你需要使用std::less
,因为这定义了通常指针的顺序:
struct cmp
{
bool operator()(int* a, int* b) const { return std::less<int*>{}(a, b); };
};
同样,您还需要将此比较器传递给std::set_intersection
。
现场演示:https://godbolt.org/z/tLdfqn。
您正在混合传递给std::set
和std::set_intersection
的比较函数。当传递给std::set
时,Compare
函数用于排序,因为它是键比较函数。当传递给std::set_intersection
时,它用于定义交集。
请尝试以下操作:
#include <iostream>
#include <cstdlib>
#include <set>
#include <algorithm>
struct cmp {
bool operator()(int *a, int *b) const {
return *a < *b;
}
};
using stupid_set = std::set<int*, cmp>;
int main() {
int* n5 = new int(5);
int* n9 = new int(9);
int* n7 = new int(7);
stupid_set s0 {n5, n9, n7};
stupid_set s1 {n9};
stupid_set i;
for (auto s : s0) {
std::cout << "s0:" << *s << std::endl;
}
for (auto s:s1) {
std::cout << "s1:" << *s << std::endl;
}
std::set_intersection(
s0.begin(),
s0.end(),
s1.begin(),
s1.end(),
std::inserter(i, i.begin()),
cmp()
);
for (auto x : i) {
std::cout << "Int=" << *x << std::endl;
}
}
查看直播
相关文章:
- std::设置自定义比较器
- set_intersection使用自定义设置比较器
- 自定义 QML QQuick彩绘项目成员锚点未在 qml 中设置为父级
- 如何在C++中将自定义文本设置为 QLabel?
- 重载C++中的[]运算符以支持自定义设置函数
- 如何在cmake工具链文件中设置编译功能,以便已知的自定义编译器使用target_compile_features
- 如何自定义设置随机的范围?
- 谷歌基准自定义设置和拆卸方法
- 设置自定义收集器时不会提升::log尊重关键字::max_size吗?
- 如何通过自定义的流设置流的坏位
- 为自定义路径类型设置提升property_tree
- Qt自定义小部件外观在设置样式表后没有变化
- openCV Mat 中的值在自定义类构造函数中设置后不会保留
- 我们无法在 Windows 10 中设置自定义密码过滤器
- 如何设置"this"线程的自定义名称?
- 设置所需DLL文件的自定义路径:电子应用
- 当我添加自定义比较器时,无法插入新元素以设置
- 如何设置此视觉工作室 (2015) 自定义生成步骤(工具?基本上,我想要一个修改头文件(c ++)的预处理器步骤
- 尝试在自定义 QT 创建器文本编辑器中创建查找和替换循环.我似乎无法设置光标位置
- C++中对集的自定义设置比较器