C++ Primer5 第四章课后练习 笔记

典型算术运算规则:

C++11标准规定,两整数相除,商一律向0取整。

取余:m%(-n)等于m%n,(-m)%n等于-(m%n)

编写程序,使用条件运算符从vector<int>中找到哪些元素是奇数,然后将这些数翻倍

#include<iostream>
#include<vector>
#include<ctime>
#include<cstdlib>

using namespace std;

int main()
{
    const int sz = 10;                     //使用sz作为数组的维度
    vector<int> vInt;
    srand((unsigned)time(NULL));           //生成随机数的种子
    //使用普通for循环为数组赋初始值
    cout << "数组的初始值是:" << endl;
    for(int i = 0; i < sz; i++)
    {
        vInt.push_back(rand() % 100);      //生成100以内的随机数
        cout << vInt[i] << " ";
    }
    cout << endl;
    //使用范围for循环将数组中的奇数翻倍
    for(auto &val : vInt)
        val = (val % 2 != 0) ? val * 2 : val;   //条件表达式
    //使用for循环和迭代器输出数组的当前值
    cout << "调整后的数组是:" << endl;
    for(auto it = vInt.cbegin(); it != vInt.cend(); ++it)
        cout << *it << " ";
    cout << endl;
    return 0;
}

当sizeof()的运算对象是数组名、数组内容、指针时

    int x[10]; 
    int *p = x;
    cout << sizeof(x)/sizeof(*x) << endl;  //10
    cout << sizeof(p)/sizeof(*p) << endl;  //2
    cout << sizeof(p) << endl;             //8

小贴士:

    //条件运算符的优先级高于逗号运算符
    someValue ? ++x,++y : --x,--y;//等价于(someValue ? ++x,++y : --x),--y

利用static_cast执行强制类型转换,对于底层const则使用const_cast

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值