STL设置自定义排序 [英] STL set custom sort
问题描述
当我意识到这是不可能使用一个集合,我试图使用一个集合创建一个新的集合,并有自定义排序功能。我在线研究,并试图实现自己的自定义排序功能,但不知道如何去
I was trying to resort a set when i realised that it was impossible to resort a set and i had to create a new set and have a custom sort function to resort it . I researched online and tried to implement my own custom sort function but am not sure how to go about it
这是我的类
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值排序,我想根据
Currently it is sorted according to x values followed by y values , I want to resort it according to
y值后跟x值
y values followed by x values
因此我实现了这个自定义排序
hence i implemented this custom sort
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;
}
这是我的示例代码, / p>
This is my sample code of how i am trying to resort the set ,
#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; ;
}
有人可以帮我吗?
推荐答案
这将是一个更简单的方法:
This would be an easier way to do it:
#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支持,但如果你没有它,你可以使用
中的
或如果您没有TR1,则 std :: tr1 :: tie
< tr1 / tuple> boost :: tie
。
Edit: std::tie
requires C++11 support, but if you don't have it you can use std::tr1::tie
from <tr1/tuple>
, or boost::tie
if you don't have TR1.
这篇关于STL设置自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!