# C++编程填空：矩阵排序

``````#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Mat{
int h,w;
public:
Mat(int height,int width):h(height),w(width)
// 在此处补充你的代码
int main()
{
vector<Mat> m;
m.push_back(Mat(2,2));
m.push_back(Mat(3,4));
m.push_back(Mat(2,2));
cin >> m[0] >> m[1] >> m[2];
sort(m.begin(),m.end());
cout<< m[0] << endl << m[1] << endl << m[2] <<endl;
cout<<"*************"<<endl;
sort(m.begin(),m.end(),comparator_1);
cout<< m[0] << endl << m[1] << endl << m[2] <<endl;
cout<<"*************"<<endl;
sort(m.begin(),m.end(),comparator_2());
cout<< m[0] << endl << m[1] << endl << m[2] <<endl;
return 0;
}
``````

（矩阵排列方式与输入相同，每个元素后用一个空格进行分隔）

``````2 3
3 4
0 12 -3 -4
-2  2 -1  0
-1 -1 -1 -1
-1 3
-2 4
``````

``````-1 3
-2 4

2 3
3 4

0 12 -3 -4
-2 2 -1 0
-1 -1 -1 -1

*************
0 12 -3 -4
-2 2 -1 0
-1 -1 -1 -1

-1 3
-2 4

2 3
3 4

*************
2 3
3 4

0 12 -3 -4
-2 2 -1 0
-1 -1 -1 -1

-1 3
-2 4
``````
• 写回答

#### 1条回答默认 最新

• threenewbee 2019-04-28 12:49
关注
``````// Q759043.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Mat{
int h,w;
public:
Mat(int height,int width):h(height),w(width)
// 在此处补充你的代码
{
p = new int[h * w];
id = ++cnt;
}
int *p;
int id;
friend istream& operator>> (istream&, Mat&);
friend ostream& operator<< (ostream&, Mat&);
friend bool comparator_1(Mat a, Mat b);
friend bool comparator_2(Mat a, Mat b);
bool operator< (const Mat& other) const
{
return h * w < other.h * other.w;
}
static int cnt;
};

int Mat::cnt = 0;

istream& operator >> (istream& input, Mat& m)
{
for (int i = 0; i < m.h * m.w; i++)
input >> m.p[i];
return input;
}

ostream& operator<<(ostream& output, Mat& m)
{
for (int i = 0; i < m.h; i++)
{
for (int j = 0; j < m.w; j++)
output << m.p[i * m.w + j] << " ";
output << endl;
}
return output;
}

bool comparator_1(Mat a, Mat b) {
int sum1 = 0;
for (int i = 0; i < a.h * a.w; i++)
sum1 += a.p[i];
int sum2 = 0;
for (int i = 0; i < b.h * b.w; i++)
sum2 += b.p[i];
return sum1 < sum2;
}

bool comparator_2(Mat a, Mat b) {
return a.id < b.id;
}

int main()
{
vector<Mat> m;
m.push_back(Mat(2,2));
m.push_back(Mat(3,4));
m.push_back(Mat(2,2));
cin >> m[0] >> m[1] >> m[2];
sort(m.begin(),m.end());
cout<< m[0] << endl << m[1] << endl << m[2] <<endl;
cout<<"*************"<<endl;
sort(m.begin(),m.end(),comparator_1);
cout<< m[0] << endl << m[1] << endl << m[2] <<endl;
cout<<"*************"<<endl;
sort(m.begin(),m.end(),comparator_2);
cout<< m[0] << endl << m[1] << endl << m[2] <<endl;
return 0;
}

``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 大一Python字典
• ¥15 multisim电路设计（相关搜索：设计报告）
• ¥15 从github上下载的项目到ecplise上咋运行
• ¥15 PC-lint Plus
• ¥15 gpl24676注释
• ¥15 php5.3内存泄露
• ¥15 DigSilent如何复制复合模型到自己案例？
• ¥15 求日版华为b610s-77a 官方公版固件，有偿
• ¥15 关于#java#的问题，请各位专家解答！（相关搜索：java程序）
• ¥15 linux tsi721的驱动编译后 insmod 提示 报错