当我意识到它是 impossible to resort a set and i had to create a new set and have a custom sort function to resort it 时,我正在尝试使用一组.我 researched online并尝试实现我自己的自定义排序功能,但我不确定如何去做
这是我的类(class)
class Point2D
{
public:
int getX() const;
int getY() const;
void setX(int);
void setY(int);
bool operator < ( const Point2D& x2) const
{
if ( x != x2.x)
{
return x < x2.x;
}
if ( y != x2.y)
{
return y < x2.y;
}
};
protected:
int x;
int y;
};
目前是先x后y排序,我想按照
y values followed by x values
因此我实现了这个自定义排序
bool p2d_sortby_y(Point2D& ptd1 , Point2D& ptd2) //custom sort function
{
if ( ptd1.getY() != ptd2.getY())
{
return ptd1.getY() < ptd2.getY();
}
if ( ptd1.getX() != ptd2.getX() )
{
return ptd1.getX() < ptd2.getX();
}
return false;
}
这是我尝试求助集合的示例代码,
#include <iostream>
#include <string>
#include <fstream>
#include <set>
#include <cmath>
using namespace std;
class Point2D
{
public:
int getX() const;
int getY() const;
void setX(int);
void setY(int);
bool operator < ( const Point2D& x2) const
{
if ( x != x2.x)
{
return x < x2.x;
}
if ( y != x2.y)
{
return y < x2.y;
}
};
protected:
int x;
int y;
};
bool p2d_sortby_y(Point2D& ptd1 , Point2D& ptd2) //custom sort function
{
if ( ptd1.getY() != ptd2.getY())
{
return ptd1.getY() < ptd2.getY();
}
if ( ptd1.getX() != ptd2.getX() )
{
return ptd1.getX() < ptd2.getX();
}
return false;
}
int main()
{
set<Point2D> p2d_set;
Point2D p2d;
p2d.setX(1);
p2d.setY(3);
p2d_set.insert(p2d);
p2d.setX(3);
p2d.setY(2);
p2d_set.insert(p2d);
set<Point2D>::iterator p2 = p2d_set.begin();
while ( p2 != p2d_set.end() )
{
cout<<p2->getX()
<<" "
<<p2->getY()
<<endl;
p2++;
}
set<Point2D,p2d_sortby_y> p2d_set2 = p2d_set; // i am unsure of how to implement the custom sort function here
}
int Point2D::getX() const
{
return x;
}
int Point2D::getY() const
{
return y;
}
void Point2D::setX(int x1)
{
x = x1;
}
void Point2D::setY(int y1)
{
y = y1; ;
}
谁能帮帮我谢谢??
最佳答案
这样做会更简单:
#include <tuple>
struct SortByYX
{
bool operator ()(const Point2D& lhs, const Point2D& rhs) const
{
return std::tie(lhs.y, lhs.x) < std::tie(rhs.y, rhs.x);
}
};
然后
set<Point2D, SortByYX> p2d_set2(p2d_set.begin(), p2d_set.end());
编辑:std::tie
需要 C++11 支持,但如果你没有它,你可以使用 std::tr1::tie
来自 <tr1/tuple>
, 或 boost::tie
如果您没有 TR1。
关于c++ - STL 设置自定义排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19979212/