在用二维数组做排序得过程中,出现得一些问题,下面先看代码,代码内容可以忽视
#include<iostream>
#include<stack>
#include<string>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
bool cmp( int *c, int *b) {
if (c[0] == b[0]) {
return c[2] < b[2];
}
else
return c[0] < b[0];
}
int main(void)
{
int t;
int a[3][300]; //问题所在
while (cin >> t) {
memset(a, 0, sizeof(a) * 4);
for (int i = 0; i < t; i++) {
cin >> a[0][i] >> a[1][i];
a[2][i] = a[1][i] - a[0][i];
}
sort(a, a + t, cmp);
int sum = 0, book[300], last_end = 0;
memset(book, 0, sizeof(book));
for (int j = 0; j < t; j++) {
if (book[a[0][j]] == 0&&a[1][j]>=last_end) {
book[a[0][j]] = 1;
last_end = a[1][j];
sum++;
}
}
cout << sum << endl;
}
}
在这个代码里面,二维数组是直接定义的,即int a[3][300],然而出现了下面的报错
根据上图,文件下面显示的algorithm可以看出,在将数组a带入sort函数时出现了错误,捣鼓了一段时间发现,用new来申请数组空间的指针数组能解决这个问题,如下代码
#include<iostream>
#include<stack>
#include<string>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
bool cmp(int *c, int *b) {
if (c[0] == b[0]) {
return c[2] < b[2];
}
else
return c[0] < b[0];
}
int main(void)
{
int t;
while (cin >> t) {
int **a = new int*[4];
for (int k = 0; k < 4; k++) { //修改的地方
a[k] = new int[t]; //
}
for (int i = 0; i < t; i++) {
cin >> a[0][i] >> a[1][i];
a[2][i] = a[1][i] - a[0][i];
}
sort(a, a + t, cmp);
int sum = 0, book[300], last_end = 0;
memset(book, 0, sizeof(book));
for (int j = 0; j < t; j++) {
if (book[a[0][j]] == 0 && a[1][j] >= last_end) {
book[a[0][j]] = 1;
last_end = a[1][j];
sum++;
}
}
cout << sum << endl;
}
}