【发布时间】:2021-10-23 06:17:04
【问题描述】:
我有一个名为Example 的类,其中包含两个整数元素a 和b,使用该类创建了一个set,并自定义了comparator。 comparator 使用第二个变量b 作为更高的优先级,按降序排列。如果该值相同,则第一个变量将具有较高值的优先级。这是我的代码:
[C++ 14 ISO]
#include <iostream>
#include <set>
using namespace std;
class Example
{
public:
int a;
int b;
Example(int x, int y) { a=x; b=y; }
};
class Comparator
{
public:
using is_transparent = true_type;
bool operator()(const int &left, const Example& right) const
{
if(left > right.b) return true;
if(left == right.b) return left > right.a ? true: false;
return false;
}
bool operator()(const Example& left, const int& right) const
{
if(left.b > right) return true;
if(left.b == right) return left.a > right ? true: false;
return false;
}
bool operator()(const Example& left, const Example& right) const
{
if(left.b > right.b) return true;
if(left.b == right.b) return left.a > right.a ? true: false;
return false;
}
};
int main()
{
set<Example, Comparator> sa;
sa.emplace(Example(4,3));
sa.emplace(Example(1,2));
sa.emplace(Example(5,3));
sa.emplace(Example(2,7));
sa.emplace(Example(3,1));
for(auto it=sa.begin(); it!=sa.end(); it++)
cout<< it->a <<" "<< it->b<<endl;
cout<<"Find: "<<endl;
auto it=sa.find(3);
if(it!=sa.end())
cout << it->a<<" " << it->b << endl;
return 0;
}
输出:
2 7
5 3
4 3
1 2
3 1
Find:
使用上述比较器找不到值3。
有人告诉我,在使用自定义比较器的情况下,如何使用set 数据在Example 类中找到变量a 的第一个值?
当我使用下面的比较器时,与仅第一个变量a相比,按升序和降序排序时效果很好。
class Comparator
{
public:
using is_transparent = true_type;
bool operator()(const int & left, const Example& right) const
{
return left < right.a;
}
bool operator()(const Example & left, const int& right) const
{
return left.a < right;
}
bool operator()(const Example& left, const Example& right) const
{
return left.a < right.a;
}
};
输出:
1 2
2 7
3 1
4 3
5 3
Find:
3 1
【问题讨论】:
-
3将等同于带有您的比较器的Example(3, 3),它在集合中不存在。 -
顺便说一句
return left > right.a ? true: false;只是return left > right.a; -
你可以使用
std::find_if但可能std::set是错误的容器 -
@463035818_is_not_a_number 是的,这里只有关系运算符足以用于布尔输出。我认为
std::find_if的复杂度与 O(n) 呈线性关系。
标签: c++ stl set comparator