往常的动态数组写法都是vector 感觉有点比美观 现在提供一种新的动态数组写法
int *a = new int[n];
感觉这种直接操作内存的写法比较直观 不过二维数组研究出来,遇到再说
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
scanf("%d", &n);
int *a = new int[n];
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
sort(a, a + n);
for (int i = 0; i < n; i++) {
cout << a[i] << ' ';
}
}
并且,更为神奇的,结构体数组本身就支持动态,如以下代码
#include <bits/stdc++.h>
using namespace std;
struct S
{
int t;
bool operator < (S s) {
return t < s.t;
}
};
int main()
{
int n;
scanf("%d", &n);
S s[n];
for (int i = 0; i < n; i++) {
scanf("%d", &s[i].t);
}
sort(s, s + n);
for (int i = 0; i < n; i++) {
cout << s[i].t << ' ';
}
}