书上说到2D数组时,用了这个例子:
#include
<
iostream
>
const
int
Cities
=
5
;
const
int
Years
=
4
;
int
main()
{
using
namespace
std;
const
char
*
cities[Cities]
=
{
"
Gribble city
"
,
"
Gribble town
"
,
"
New Gribble
"
,
"
San Gribble
"
,
"
Gribble Vista
"
};
int
maxtemps[Years][Cities]
=
{
{
95
,
99
,
86
,
100
,
104
},
{
95
,
97
,
90
,
106
,
102
},
{
96
,
100
,
940
,
107
,
105
},
{
97
,
102
,
89
,
108
,
104
}
};
cout
<<
"
Maximum tempevatures for 2002 - 2005\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;
}
cin.
get
();
return
0
;
}
完了之后,书上说,可以这样定义cities 2D数组:
const char cities[25][Cities]=
{
"Gribble city",
"Gribble town",
"New Gribble",
"San Gribble",
"Gribble Vista"
};
书上说:这样定义,你就保证每个地名不超过24个字符。当初看到这段代码,我百思不得其解:25行,每行5列(Cities常量)???也就是说,有25个城市,每个城市的名称不能超过4个字符(字符串还得加个“\0”),这是正确的吗?
编译器告诉我,这样写是错的!
按照自己的理解改成:
const char cities[Cities][25]=
{
"Gribble city",
"Gribble town",
"New Gribble",
"San Gribble",
"Gribble Vista"
};
顺利通过编译,并且结果和原例一样。
当然,改成string更简单,也更好理解。不过,这时候就是一维数组了:
const string cities[Cities]=
{
"Gribble city",
"Gribble town",
"New Gribble",
"San Gribble",
"Gribble Vista"
};
我更喜欢用string,因为我是从VB转过来的,习惯了string;同时,书上都说了,string是C++对C的扩充,是面向对象的~
posted on 2006-04-12 16:15
蕃豆仁 阅读(494)
评论(0) 编辑 收藏 引用 所属分类:
C++ primer plus读书笔记