c++ - How to have set of struct using custom comparator function instead of operator overloading
问题描述
I want to insert instances of structs into a set. I know that to do this the < operator has to be overloaded so that set can make a comparison in order to do the insertion.
Following program works perfectly.
#include <iostream>
#include<set>
using namespace std;
struct Node
{
int x;
int y;
};
bool operator <( const Node &a,const Node &b)
{
return a.x < b.x ||( a.x == b.x && a.y < b.y);
}
int main()
{
set<Node> s;
Node node;
node.x = 1;
node.y = 2;
s.insert(node);
node.x = 1;
node.y = 0;
s.insert(node);
for( Node node : s)
cout << node.x <<","<< node.y <<endl;
}
Output :
1,0
1,2
But if I want to use custom comparator function,instead of operator overloading I tried this way.
bool Comp( const Node &a,const Node &b)
{
return a.x < b.x ||( a.x == b.x && a.y < b.y);
}
And in main() , I define set as this way.
set<Node, Comp> s; // error
But I got following error :
type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Compare, class _Alloc> class std::set’ set<Node, Comp> s;
Can anyone explain, why there is a error ? How to rectify it ?
解决方案
您可以使用函数指针:
bool Comp(const Node &lhs, const Node &rhs)
{
return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}
set<Node, bool (*)(const Node&, const Node&)> s(&Comp);
甚至更好的仿函数(因为比较器是固定的):
struct Comp
{
bool operator() (const Node &lhs, const Node &rhs) const
{
return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}
};
set<Node, Comp> s;
推荐阅读
- c# - 在连接字符串中包含服务名称的语法是什么?
- image - 从 RGB 值重绘后,图像现在具有黄色色调
- c - 是否可以将函数的返回值作为 C 中主函数的返回值传递?
- mysql - 重命名 Django 模型时的最佳实践是什么?[数据库:MySQL、PostgreSQL 或 SQLite]
- excel - 是否可以使用 OpenXML SDK 创建加密的 Excel 文件
- fb-hydra - 确认递归实例化将允许分层对象实例化
- java - 使用 CommonsCli,我如何解析一个可以多次出现并且具有灵活数量的值的选项?
- dataframe - 使用 DataFramesMeta 包中的 @linq 在 Julia 中整理数据
- ios - 颤动的网页视图不适用于 ios 应用程序
- mongodb - MongoDB:如何在分页期间根据表达式/条件设置 mongo 实体中字段的值并对该字段进行排序