【发布时间】:2021-03-17 18:42:30
【问题描述】:
对于 C++ STL set,我需要自定义比较,但我的代码存在严重问题。使用 Visual Studio 2019 编译失败。第一个错误是(在 xutility 中)“错误 C2672: 'operator __surrogate_func': 找不到匹配的重载函数”。
代码如下:
#include <set>
struct P
{
char a;
char b;
char c;
};
class PSortingCriterion
{
public:
bool operator() (const P &p1, const P &p2) const
{
if(p1.a != p2.a)
return p1.a < p2.a;
else if(p1.b != p2.b)
return p1.b < p2.b;
else if(p1.c != p2.c)
return p1.c < p2.c;
else
return false; // p1 == p2
}
};
std::set<P, PSortingCriterion> s1, s2, diff;
void F(void)
{
if(s1 != s2) // errors are all due to this statement; no errors if it's removed
{
}
}
更新:按照 Igor Tandetnik 的建议,我修改了代码,但仍然无法编译(与上述相同的错误)。
新代码:
#include <set>
#include <algorithm>
#include <iterator>
struct P
{
char a;
char b;
char c;
};
class PSortingCriterion
{
public:
bool operator() (const P &p1, const P &p2) const
{
if(p1.a != p2.a)
return p1.a < p2.a;
else if(p1.b != p2.b)
return p1.b < p2.b;
else if(p1.c != p2.c)
return p1.c < p2.c;
else
return false; // p1 == p2
}
};
std::set<P, PSortingCriterion> s1, s2, diff;
void F(void)
{
set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(diff, diff.begin()));
}
【问题讨论】:
标签: stl set comparator