- 10
- 0
- 约 95页
- 2017-02-04 发布于江苏
- 举报
第四讲 数组与vector Arrays 包含同一数据类型的数据结构 占用一段连续的内存空间 创建后大小不能改变 通过索引的方式访问数组中的元素 Declaring an array 类型、数组名、数组大小 如:int c[ 12 ]; 数组大小为大于 0 的常整数 用初始化列表来初始化数组成员 例:int n[] = { 10, 20, 30, 40, 50 }; 如果初始化列表的数据量小于数组长度,其余数组元素将被初始化为 0 例:int n[ 10 ] = { 0 }; 如果初始化列表的数据量大于数组长度,产生编译错误 可以使用循环语句给数组的元素赋初值 Declare array, specify number of elements Use repetition statement to loop for each element Use body of repetition statement to initialize each individual array element 使用 initializer list 给数组的元素赋初值 Initializer list Items enclosed in braces ({}) Items in list separated by commas Example int n[] = { 10, 20, 30, 40, 50 }; Because array size is omitted in the declaration, the compiler determines the size of the array based on the size of the initializer list Creates a five-element array Index values are 0, 1, 2, 3, 4 Initialized to values 10, 20, 30, 40, 50, respectively Initializing an array in a declaration with an initializer list (Cont.) 如果初始化列表中的数据个数比数组元素少 Remaining elements are initialized to zero Example int n[ 10 ] = { 0 }; Explicitly initializes first element to zero Implicitly initializes remaining nine elements to zero 如果初始化列表中的数据个数比数组元素多 Compilation error Constant variables const 修饰符,又称为常量或只读变量 声明时必须进行初始化,且以后不能修改 使用常量变量来声明数组长度使程序更加灵活,避免了 “magic numbers” 用字符数组来存储和处理字符串 char string1[] = { f, i, r, s, t, \0 }; char string1[]=“first”; -- 正确! char string1[]=‘first’; -- 错误! cin string1; 以 ’\0’ 结尾的字符数组可以通过 cout 进行输出 Using character arrays to store and manipulate strings Can be initialized using a string literal Example char string1[] = Hi; Equivalent to char string1[] = { H, i, \0 }; Array contains each character plus a special string-termination character called the null character (\0) Can also be initialized with individual character constants in an initializer list char string1[] = {f,i,r,s,t,\0 }; Can also input a string directly into a character array from the keyboard using cin and cin string1; cin may read more characters than the array can store, may cause other
您可能关注的文档
最近下载
- 现代饭店管理(课件).doc VIP
- 2024-2025学年广东省深圳市龙岗区六年级(上)期末语文试卷.pdf VIP
- 2025-2026学年内蒙古乌兰察布市初中联盟校八年级(上)期末数学试卷(含答案).pdf VIP
- (一模)哈三中2025届高三第一次模拟考试 化学试题(含答案).pdf
- Yamaha 雅马哈 乐器音响 PSR-E383 PSR-EW320 YPT-380 YPT-W320 Reference Manual 用户手册.pdf
- 医患沟通话术集锦.pdf VIP
- 2025年江苏常州初中学业水平考试英语试卷试题(含答案详解).docx VIP
- (一模)2026年合肥市高三第一次教学质量检测英语试卷(含答案)+听力音频+听力原文.docx
- 2023年山东泰安初中学业水平考试生物试卷真题(精校版).docx VIP
- 2024年山东青岛初中学业水平考试生物卷试题真题(精校打印版).pdf VIP
原创力文档

文档评论(0)