2.3.5 巢狀迴圈和二維陣列
阿新 • • 發佈:2021-02-10
技術標籤:基礎學習 - C++c++
文章目錄
巢狀迴圈和二維陣列
1 二維陣列宣告
int maxtemps[4][5];
2 二維陣列初始化
int maxtemps[4][5] =
{
{ 96, 100, 87, 101, 105 },
{ 96, 98, 91, 107, 104 },
{ 97, 101, 93, 108, 107 },
{ 98, 103, 95, 109, 108 }
};
3 二維陣列使用
#include <iostream>
const int Cityes = 5;
const int Years = 4;
int main()
{
using namespace std;
const char* cities[Cityes] =
{
"北京",
"天津",
"上海",
"黑龍江",
"江蘇"
};
int maxtemps[Years][Cityes] =
{
{ 96, 100, 87, 101, 105 },
{ 96, 98, 91, 107, 104 },
{ 97, 101, 93, 108, 107 },
{ 98, 103, 95, 109, 108 }
};
cout << "最高溫度 2008 - 2011\n\n";
for (int city = 0; city < Cityes; city++)
{
cout << cities[city] << ":\t";
for (int year = 0; year < Years; year++)
{
cout << maxtemps[year][city] << '\t';
}
cout << endl;
}
return 0;
}
- 可以使用
char
陣列的陣列,而不是字串陣列,宣告如下
char cities[25] =
{
"北京",
"天津",
"上海",
"黑龍江",
"江蘇"
};
- 使用
string
物件陣列
const string cities[Cityes] =
{
"北京",
"天津",
"上海",
"黑龍江",
"江蘇"
};
如果字串是可修改的,則應該省略限定符const
。
使用string
物件陣列時,初始化列表和用於顯示字串的for
迴圈程式碼與前兩種方法相同。
在希望字串是可修改的前提下,string
類的自動調整大小的特性可以更好的完成工作