我想对vector<vector<double> >
进行排序,并使用vector<int>
ex A[0][1].............[N], and A[0][0] = X, A[0][1] = Y, A[0][2] = Z
A[0] = (1,5,3), A[1] = (3,2,1) A[2] = (2,8,4) after sorting
index: 0 1 2
A[0] = (1,5,3), A[1] = (2,8,4) A[2] = (3,2,1)
original index : 0 2 1
所以我编写了以下代码,我想使用STL排序,但我不知道如何编写比较函数。
class point{
public:
point(int totalLength = 0, int elementLength = 0);
vector<vector<double> > pointSet;
vector<double> pointIndex;
};
point::point(int totalLength, int elementLength){
pointSet.resize(totalLength,vector<double>(elementLength, 0));
pointIndex.resize(elementLength);
}
和建议或其他方式实现它?
感谢您的阅读。
答案 0 :(得分:1)
我要说的第一件事是为点引入单独的数据结构。通常,当您谈论点和某些几何体时,您就会知道确切的数字尺寸。 所以,你可以使用
struct Point
{
double x;
double y;
double z;
};
而不是
std::vector<double>
即使您不知道尺寸数量,也最好使用
typedef std::vector<double> Point;
表示单点。
您的std::vector<std::vector<double> >
变为std::vector<Point>
。它至少更容易阅读。
然后,使用std::sort
无法同时对2个数组进行排序。因此,您必须将pointSet
和pointIndex
数组合并到一个数据结构中进行排序。
显而易见,您可以创建
typedef std::pair<Point, int> IndexedPoint;
std::vector<IndexedPoint> indexedPoints;
然后用给定的点及其索引填充此结构,然后排序:
for(int indx = 0; indx < pointsSet.size(); ++indx) {
indexedPoints.push_back(std::make_pair(pointsSet[indx], indx));
}
std::sort(indexedPoints.begin(), indexedPoints.end(), &lessThen);
少实现取决于比较算法。例如,如果要比较第一个坐标,可以编写
bool lessThen(const IndexedPoint& l, const IndexedPoint& r)
{
return l.first.x < r.first.x; //or return l.first[0] < r.first[0]; -- ensure point has at lest 1 dimension here!
}