二维数组用sort排序遇到得问题

在用二维数组做排序得过程中,出现得一些问题,下面先看代码,代码内容可以忽视

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值