gpt4 book ai didi

C++,比较器,函数指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:36:06 26 4
gpt4 key购买 nike

我想根据 x 或 y 坐标创建排序的点集。

typedef std::set <Point2D, sorter> Points;

对于“点”的类型,我想使用不同的比较器。第一个根据 x 坐标对点进行排序,第二个根据 y 坐标对点进行排序:

typedef std::set <Point2D, sortPointsByX()> Points;
typedef std::set <Point2D, sortPointsByy()> Points;

在哪里

class sortPoints2DByX
{
public:

bool operator() ( const Point2D &p1, const Point2D &p2 );

};

class sortPoints2DByY
{
public:

bool operator() ( const Point2D &p1, const Point2D &p2 );

};

是否可以在 Points 声明中创建指向构造函数 sortPoints2DByX/sortPoints2DByY 类的指针

typedef std::set <Point2D, pointer_to_somparator_class> Points;

以及是否需要使用它们中的任何一个?

我需要一种数据类型可以用两种方式排序。

如果这个想法是错误的,有没有更合适的解决方案?

我需要计算 x 和 y 坐标的中值...

感谢您的帮助...

最佳答案

Is it possible to create a pointer to the constructor sortPoints2DByX/sortPoints2DByY classes in Points declaration?

不,您不能将地址作为类的构造函数。

I need to have one data type can be sorted in two ways.

您可以使用指向函数的指针。示例实现:

#include <algorithm>
#include <set>
#include <iostream>

// Your implementation may differ.
struct Point
{
int x; int y;
Point(int x_, int y_)
: x(x_), y(y_) {}
};

// For display purposes.
void print(const Point& point)
{
std::cout << '(' << point.x
<< ',' << point.y << ')' << std::endl;
}

bool OrderByX ( const Point& lhs, const Point& rhs )
{
return (lhs.x < rhs.x);
}

bool OrderByY ( const Point& lhs, const Point& rhs )
{
return (lhs.y < rhs.y);
}

// Type of comparison operator.
typedef bool(*Comparator)
(const Point&lhs,const Point&rhs);

// Set used to store points in sorted order.
typedef std::set<Point, Comparator> Points;

int main ( int, char ** )
{
// Each set ordered with it's own criteria.
Points by_x(&OrderByX);
Points by_y(&OrderByY);

// Insert each point in both sets.
by_x.insert(Point(1,2)); by_y.insert(Point(1,2));
by_x.insert(Point(3,1)); by_y.insert(Point(3,1));
by_x.insert(Point(4,3)); by_y.insert(Point(4,3));
by_x.insert(Point(2,4)); by_y.insert(Point(2,4));

// Show that 1st set is in proper order.
std::cout << "Sorted by X:" << std::endl;
std::for_each(by_x.begin(), by_x.end(), &print);
std::cout << std::endl;

// Show that 2nd set is in proper order.
std::cout << "Sorted by Y:" << std::endl;
std::for_each(by_y.begin(), by_y.end(), &print);
std::cout << std::endl;
}

它生成以下输出:

Sorted by X:
(1,2)
(2,4)
(3,1)
(4,3)

Sorted by Y:
(3,1)
(1,2)
(4,3)
(2,4)

关于C++,比较器,函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4174431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com