Ch数组与向量.pptVIP

  • 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

文档评论(0)

1亿VIP精品文档

相关文档