二维数组的声明形式
例如:int maxtemps[4] [5]
其中,maxtemps是数组名,是一个包含4个元素的数组,其中每个元素都是一个5个整数组成的数组。可以将maxtemps看成是由4行组成,每一行有5个元素。
索引方式:
例如:maxtemps[i][j]表示第i行,第j列的元素。
初始化数组
#include <iostream>
int main()
{
using namespace std;
int maxtemps[4][5] =
{
{96, 100, 87, 101, 105},
{96, 98, 91, 107, 104},
{97, 101, 93, 108, 107},
{98, 103, 95, 109, 108}
};
cout << maxtemps[0][0];
return 0;
}
96
使用二维数组
#include <iostream>
const int Cities = 5;
const int Years = 4;
int main()
{
using namespace std;
const char * cities[Cities] =
{
"Gribble City",
"Gribbletown",
"New Gribble",
"San Gribble",
"Gribble Vista"
};//指针数组存储5个字符串的地址
//这里也可使用char数组的数组,这里将5个字符串的最大长度限制为24个字符,
/*
char cities[Cities][25] =
{
"Gribble City",
"Gribbletown",
"New Gribble",
"San Gribble",
"Gribble Vista"
};
char数组的数组,将5个字符串分别复制到5个包含25个元素的char数组中,所以使用指针数组更经济
但是如果您想要修改其中的任何一个字符串,则这个二维数组更方便
*/
/*
const string cities[Cities] =
{
"Gribble City",
"Gribbletown",
"New Gribble",
"San Gribble",
"Gribble Vista"
};
也可以使用string对象数组,而不是字符串指针数组,如果希望字符串是可修改的,应该忽略限定符const
在希望字符串是可修改的情况下,string类自动调整大小的特性使其更加方便。
*/
int maxtemps[Years][Cities] =
{
{96, 100, 87, 101, 105},
{96, 98, 91, 107, 104},
{97, 101, 93, 108, 107},
{98, 103, 95, 109, 108}
};
cout << "Maximum temperatures for 2008-2011\n\n";
for (int city = 0; city < Cities; ++city)
{
cout << cities[city] << ":\t";
for (int year = 0; year <Years; ++year)
cout << maxtemps[year][city] << "\t";
cout << endl;
}
return 0;
}
Maximum temperatures for 2008-2011
Gribble City: 96 96 97 98
Gribbletown: 100 98 101 103
New Gribble: 87 91 93 95
San Gribble: 101 107 108 109
Gribble Vista: 105 104 107 108