自己老是忘掉,所以干脆写一个在博客存着。另外,附上两道题:1 二维数组中的查值 2 顺时针打印一个二维数组
C++创建动态数组:
一维数组:
int *x = new int [size];
delete [] x;
二维数组,直接上代码(包括如何把二维数组作为参数传递):
#include <iostream>
using namespace std;
int colFind(int **a, int row, int col)
{
for (int i = 0; i != row; ++i)
for (int j = 0; j != col; ++j)
cout << a[i][j] << endl;
return 0;
}
int main()
{
int **x = new int*[5];//分配空间
for (int i = 0; i != 5; ++i)
x[i] = new int[5];
for (int i = 0; i != 5; ++i) //数组赋值
for (int j = 0; j != 5; ++j)
x[i][j] = i * 5 + j;
colFind(x, 5, 5);//打印数组
for (int i = 0; i != 5; ++i)//撤销空间
delete[] x[i];
delete[] x;
return 0;
}
两道算法题
第一道:返回一个key元素下标的pair对,如果没找到则返回(-1,-1)。
#include <iostream>
using namespace std;
pair<int, int> FindInMat(int **x , int row, int col, int key)
{
int i = 0, j = col - 1;
while (i < row && j >= 0)
{
if (x[i][j] == key)
return make_pair(i, j);
else if (x[i][j] > key)
--j;
else
++i;
}
return make_pair(-1, -1);
}
//测试代码:
int main()
{
int **x = new int* [4];
x[0] = new int[4]{1, 2, 8, 9};
x[1] = new int[4]{2, 4, 9, 12};
x[2] = new int[4]{4, 7, 10, 13};
x[3] = new int[4]{6, 8, 11, 15};
//colFind(x, 4, 4);
cout << FindInMat(x, 4, 4, 11).first << FindInMat(x, 4, 4, 11).second;
system("pause");
return 0;
}
第二道:环形打印一个二维数组
<pre class="cpp" name="code">#include <iostream>
using namespace std;
//打印一个圈
void Print(int **a, int row, int col, int start)
{
int stopX = row - start - 1;
int stopY = col - start - 1;
if ((stopX == start) && (stopY == start))
cout << a[start][start] << endl;
else
{
for (int i = start; i <= stopX; ++i)
cout << a[start][i] << endl;
for (int i = start + 1; i <= stopY; ++i)
cout << a[i][stopX] << endl;
for (int i = stopX - 1; i >= start; --i)
cout << a[stopY][i] << endl;
if (stopY - start >= 2)
for (int i = stopY -1; i >= start + 1; --i)
cout << a[i][start] << endl;
}
}
//打印函数的实体
void PrintCircle(int **a, int row, int col)
{
if (row <= 0 || col <= 0 || a == NULL)
return;
else
{
int start = 0;
while (row > 2 * start && col > 2 * start)
{
Print(a, row, col, start);
++start;
}
}
}
//测试代码
int main()
{
int **a = new int*[5];
for (int i = 0; i != 5; ++i)
{
a[i] = new int[5];
}
for (int i = 0; i != 5; ++i)
for (int j = 0; j != 5; ++j)
a[i][j] = i * 5 + j;
PrintCircle(a, 5, 5);
system("pause");
return 0;
}