1、用vector建立二维数组:
vector<vector<int>> arr(rows);
for (int i = ; i < rows; i++)
arr[i].resize(cols);
或:
vector<vector<int>> v(m, vector<int>(n));
2、当数组已初始化但某些下标还未赋值时,此下标对应的变量为NULL(见34行)
代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std; bool cmp(int a, int b)
{
return a > b;
}
int main()
{
int n;
cin >> n;
vector<int> v(n);
for (int i = ; i < n; i++)
cin >> v[i];
sort(v.begin(), v.end(), cmp);
int s = sqrt(n);
while (n % s) s--;
int cols = s, rows = n / s;
/*
vector<vector<int>> arr(rows);
for (int i = 0; i < rows; i++)
arr[i].resize(cols);
*/
vector<vector<int>> arr(rows, vector<int>(cols));
int i = , j = , t = ;
int direction = ;
while (t < n)
{
if (direction == )
{
if (j < cols && arr[i][j] == NULL)
arr[i][j++] = v[t++];
else
{
i++;
j--;
direction = ;
}
}
else if (direction == )
{
if (i < rows && arr[i][j] == NULL)
arr[i++][j] = v[t++];
else
{
j--;
i--;
direction = ;
}
}
else if (direction == )
{
if (j >= && arr[i][j] == NULL)
arr[i][j--] = v[t++];
else
{
i--;
j++;
direction = ;
}
}
else if (direction == )
{
if (i >= && arr[i][j] == NULL)
arr[i--][j] = v[t++];
else
{
i++;
j++;
direction = ;
}
}
}
for (int i = ; i < rows; i++)
{
for (int j = ; j < cols; j++)
{
if (j) cout << " ";
cout << arr[i][j];
}
cout << endl;
}
return ;
}