C++,vector 自定义类型的排序

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


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值