C++,vector的排序
// 通过重载<,>,方便,看起来好看
// 还可以自定义比较函数
// 四个头文件,特别要注意须包含 <functional>,下面才能用less<CValue>()
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
class CValue
{
public:
int index;
double value;
public:
CValue(void){index = -1; value = 100;}
// 重载=,<,>
void operator = (const CValue& rhs){ this->index = rhs.index;this->value = rhs.value;}
bool operator < (const CValue& rhs)const{ return this->value < rhs.value;}// 升序
bool operator > (const CValue& rhs)const{ return this->value > rhs.value;}// 降序
};
void SortMatrixByRow(vector< vector<CValue> >& distMatrix)
{
int i, j;
int dist;
CValue temp;
int numCluster=7;// 本簇数据的样本个数
distMatrix.clear();distMatrix.resize(numCluster, vector<CValue>(numCluster));
for (i = 0; i < numCluster ; i++){
for (j = i+1; j < numCluster ; j++){
/*if (i < j)*/{
dist = i+j;
temp.index = j;temp.value = dist;
distMatrix[i][j] = temp;
distMatrix[j][i] = temp;
}
}
}
for (i = 0; i < numCluster ; i++){
// 如果是升序排序,则将greater<CValue>()改为less<CValue>()
sort(distMatrix[i].begin(), distMatrix[i].end(), greater<CValue>());
}
}
int main(int argc, char **argv)
{
vector< vector<CValue> > distMatrix;
SortMatrixByRow(distMatrix);
for (int i = 0; i < distMatrix.size() ; i++){
for (int j = 0; j < distMatrix[i].size() ; j++){
cout << distMatrix[i][j].value << " ";
}
cout << endl;
}
return 0;
}