当我意识到不可能重新使用集合时,我不得不尝试重新设置集合,而我不得不创建一个新集合并具有一个自定义排序函数来重新使用它。我在网上进行了研究,并尝试实现自己的自定义排序功能,但不确定如何去做
这是我的课
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值,然后是x值
因此,我实现了这种自定义排序
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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句