2013-05-04 33 views
1

动我想排序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); 
} 

和建议或其他方式来实现它?

感谢您的阅读。

+2

为什么不引入特殊的'结构Point'而不是内部'向量'? – Lol4t0 2013-05-04 19:26:37

+0

输入是一个常量向量<向量>。 – 2013-05-04 19:28:20

+2

所以,你有机会改进它,用'vector '代替(如果它实际上是点的矢量)。想想看。 – Lol4t0 2013-05-04 19:29:47

回答

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个阵列进行排序。因此,您必须将您的pointSetpointIndex数组合并到一个数据结构中进行排序。

一个明显的方式,你可以创建

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! 
}