Article Directory
Based on the range for loop
double prices[5] = {4.99, 10.99, 6.87, 9.58, 11.49};
for(double x : prices)
cout<<x<<endl;
Logical operator shorting
The &&
expression on the left, if it is determined false
, it is not determined expression / execution right
const pointers and pointers to const
*
Direct contact with the name of the pointer is a pointer to a 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
Command-line arguments (imitation C)
Code:
// 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;
}
Command line:
...>g++ option.cpp -o option.exe
...>option -i infile -o outfile
Command line output:
5 arguments in all.
1: option
2: -i
3: infile
4: -o
5: outfile
The first parameter is the path to the program, which is the program name on the command line (or full path)
C ++ will automatically spliced spaced blank / continuous string
It can be written:
cout << "Hello World!\n"
"Still water runs deep.\n"
"Can you can a can like a canner can a can?";
Generating a pseudo-random number
You need to include <ctime>
and <random>
two headers.
#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
Noting the gap between these "random number" is not great. This is because rand()
according to srand()
generate "random number" value is passed, if not Sleep(1000)
, then even the same ten numbers will appear.