a. C++ Tips

基于范围的for循环

double prices[5] = {4.99, 10.99, 6.87, 9.58, 11.49};
for(double x : prices)
    cout<<x<<endl;

逻辑运算符会短路

&&左侧的表达式若判断为false, 则不会判断/执行右侧的表达式

const指针和指向const的指针

*直接接触指针名的就是指向const的指针

int i = 10;
int j = 10;
// 变量值不可修改
const int ci = i;
ci = 1;    //error
// 1. 指针指向的内存不可修改
const int* pi1 = &i;
*pi1 = 1;   // error
pi1 = &j;
// 2. 等价于 1
int const* pi2 = &i;
*pi2 = 1;   // error
pi2 = &j;
// 3. 指针不可修改
int* const pi3 = &i;
*pi3 = 1;
pi3 = &j;   // error
// 4. 没有这种语法
const* int pi4 = &i;    // error
// const int*类型的值不能用于初始化int*变量
int* pi4 = pi1;    // error

命令行参数(仿C)

代码:

// option.exe
#include<stdio.h>

int main(int argc, char* argv[])
{
    printf("%d arguments in all.\n", argc);
    for(int i = 0; i < argc; i++)
        printf("%d: %s\n", i+1, argv[i]);
    return 0;
}

命令行输入:

...>g++ option.cpp -o option.exe

...>option -i infile -o outfile

命令行输出:

5 arguments in all.
1: option
2: -i
3: infile
4: -o
5: outfile

其中第一个参数为程序的路径, 也就是命令行中的程序名(或完整路径)

C++中会自动拼接空白隔开/连续的字符串

可以这样写:

cout << "Hello World!\n"
        "Still water runs deep.\n"
        "Can you can a can like a canner can a can?";

生成伪随机数

需要包含<ctime><random>两个头文件。

#include <Windows.h>    // for Sleep()
#include <iostream>
#include <ctime>
#include <random>
#pragma (lib, "Kernel32.lib")
using namespace std;

int main()
{
    for(int i = 0; i < 10; ++i)
    {
        srand(time(0));
        cout << "# " << i+1 << " : " << rand() << endl;
        Sleep(1000);
    }

    return 0;
}
# 1 : 16695
# 2 : 16699
# 3 : 16702
# 4 : 16705
# 5 : 16708
# 6 : 16712
# 7 : 16715
# 8 : 16718
# 9 : 16721
# 10 : 16725

注意到这些“随机数”之间的差距并不是很大。这是因为rand()根据给srand()传递的值生成“随机数”,如果没有Sleep(1000)的话甚至可能会出现十个一样的数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值