gpt4 book ai didi

c++ - 创建通用模板类以按变量对不同类进行排序

转载 作者:行者123 更新时间:2023-11-28 06:15:35 25 4
gpt4 key购买 nike

我能够分别读取文件和填充 vector 。

有没有办法创建一个模板来根据标准对各个类进行排序?我使用的方法很繁琐,我必须创建很多模板类来适应每个 vector 。

我需要一些关于创建通用模板的想法

//consist if accessors and mutator x and y
vector<Point2D> point2d;
//consist if accessors and mutator x and y and z
vector<Point3D> point3d;
//consist if accessory and mutator 2 Point2D point
vector<Line2D> line2d;
//consist if accessory and mutator 2 Point3D point
vector<Line3D> line3d;
//sort_crit is a global variable that change according to user menu
//sort_order is a global variable that change according to user menu (ASC or DSC)
if(sort_crit == "X-Coordinate") {
sortByX(point2d, point2d.size(), sort_order);
}

我的数据

Point2D, [3, 2]
Line3D, [7, 12, 3], [-9, 13, 68]
Point3D, [1, 3, 8]
Line3D, [7, -12, 3], [9, 13, 68]
Point3D, [6, 9, 5]
Point2D, [4, 8]
Line3D, [70, -120, -3], [-29, 1, 268]
Line2D, [7, 12], [-9, 4]
Line3D, [25, -69, -33], [-2, -41, 58]
Point3D, [6, 9, -50]
Point2D, [12, 80]
Point2D, [9, 8]

我当前的模板只适用于 Point2D

template <class T>
void sortByX(vector<T> a1, int size, string type) {
if (type == "ASC") {

for(int x=0; x<size; x++) {

for(int y=0; y<size-1; y++) {

if(a1[y].getX()>a1[y+1].getX()) {

int tempx = a1[y+1].getX();

a1[y+1].setX(a1[y].getX());

a1[y].setX(tempx);

int tempy = a1[y+1].getY();

a1[y+1].setY(a1[y].getY());

a1[y].setY(tempy);
}
}
}
} else if (type == "DSC") {

for(int x=0; x<size; x++) {

for(int y=0; y<size-1; y++) {

if(a1[y].getX()<a1[y+1].getX()) {

int tempx = a1[y+1].getX();

a1[y+1].setX(a1[y].getX());

a1[y].setX(tempx);

int tempy = a1[y+1].getY();

a1[y+1].setY(a1[y].getY());

a1[y].setY(tempy);
}
}
}
}
for(int x=0; x<size; x++) {
cout << a1[x] << endl;
}

}

最佳答案

std::sort 是通用排序,允许您提供自定义排序标准。

例如,对于点、线等的一些容器,l:

sort(begin(l), end(l), [](auto& a, auto& b)
{
return a.getX() < b.getX();
});

关于c++ - 创建通用模板类以按变量对不同类进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30408937/

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