【C++ Primer Plus】笔记 - 第四章 复合类型

第四章 复合类型

C++ Primer Plus自学笔记, 可能不适用于所有人, 仅供参考

4.1 数组

1. 创建数组

例: 创建一个名为months的数组,该数组有 12 个元素,每个元素存储一个short类型的值:

    short months[12];
  • months的类型不是"数组", 而是"short数组".
  • 强调了数组是使用short类型创建的.

若将一个值赋给不存在的元素months[101], 编译器不会报错, 但程序运行后可能引发一些严重问题.

  • 必须确保程序只使用有效下标值, 避免数组越界.
// arrayone.cpp
#include <iostream>

int main() {
   
   
    using namespace std;
    int yams[3];    //创建有3个元素的int型数组
    yams[0] = 7;
    yams[1] = 8;
    yams[2] = 6;

    int yamcosts[3] = {
   
   20, 30, 5};  // 创建初始化数组;

    // 使用数组元素
    cout << "Total yams = ";
    cout << yam[0] + yams[1] + yams[2] << endl;
    cout << "The package with " << yams[1] << " yams costs ";
    cout << yamcosts[1] << " cents per yam.\n";

    int total = yams[0] * yamcosts[0] + yams[1] * yamcosts[1];
    total = total + yams[2] * yamcosts[2];
    cout << "The total yam expenses is " << total << " cents.\n";

    // 数组及元素的 size 大小
    cout << "\nSize of yams array = " << sizeof yams << " bytes.\n";
    cout << "Size of one element = " << sizeof yams[0] << " bytes.\n";

    return 0;
}
  • 该程序的输出:
    Total yams = 21
    The package with 8 yams costs 30 cents per yam.
    The total yam expense is 410 cents.

    Size of yams array = 12 bytes.
    Size of one element = 4 bytes.
  • 数组的初始化:
    int cards[4] = {
   
   3, 6, 8, 10};
    int hand[4];

    float hotelTips[5] = {
   
   5.0, 2.5};    // 只初始化前两个元素.
    long totals[500] = {
   
   0};     		// 将所有元素都初始化为 0
    short things[] = {
   
   1, 5, 3, 8};  	// things 数组将包含 4 个元素.

    // C++11 数组初始化方法
    double earning[4] {
   
   1.2e4, 1.6e4, 1.1e4, 1.7e4}; // 省略等于号
    unsigned int counts[10] = {
   
   };   		// 将所有元素初始化为0.
    float balances[100] {
   
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值