C++ Primer
chapter 1 Variable, Basic type
- bool, int, char, double, float
- unsigned,long long
- Use an unsigned type when you know that the values cannot be negative
- Use double rather than float
- Don’t Mix Signed and Unsigned Types
- object is a region of memory that can contain data and has a type.
- Don’t use Uninitialized Variables
- scope of a name
- grobal scope
- block scope
Reference | Pointer |
---|---|
int &r = val | int *ptr = &val |
bind to a object | hold the address of another object |
not a object | a object |
can’t reblind to a new object | can be assigned and copied |
must be initialized | can be invaild |
Note: ModernC++ programs generally should avoid using NULL and use nullptr instead.
- void* Pointer
- it can hold the address of any object, but the type of the object at that address is unknown.
Tip:It can be easier to understand complicated pointer or reference declarations if you read them from right to left.
- const
- const int &r = i; //r is bound to i;but can’t change i;
- int *const ptr = & i; //ptr always point to i;
- const int *ptr = & i; // ptr can point to another object,but can’t change i;
- const int *const ptr = & i;
- constexpr
- auto
- auto f(){/***/} // C++14才支持
- decltype(推断函数返回类型)
- decltype(f()) i = x; // i return the type of f()
- decltype((variable))?decltype(variable)?
chapter 2 Vector,string,array
- namespace
- Headers Should Not Include using Declarations
- string
- operate
- os<<s,in>>s // 按空格记录
- getline(is,s) // 按行记录
- s.empty(), s.size()
- s[n],+,-,==,!=,>,<
- string::size_type //足够储存string的size,储存string size的变量类型,可以用auto替代
- range for语句
- for( auto i : str){ /***/}
- char
- ispunct()
- toupper()
- isspace()
- operate
- vector
- If differing element values are needed, it is usually more efficient to define an empty vector.
- operate
- push_back()
- empty(), size()
- ==, !=, <, >
- vector< int >::size_type
- 使用range for避免下标超出
- iterator
- begin(), end()
- operate
- ++it, --it, *it, ==, !=
- binary search(二分查找)
- Array
-
Tip:If you don’t know exactly how many elements you need, use a vector
-
int *ptr = &arr[0] // 或int *ptr = arr;
-
use iterator
int *beg = begin(arr), *en = end(arr); while(beg!=en) cout<<*beg++<<endl;
-
use array init vector
- vector< int>v( begin(arr), end(arr) );
-
chapter 3 Expression
- Arithmetic Operators
- 单目优先性高于双目
- “+,-”,*,/,%,+,-
- m%(-n) = m%n, (-m)%n = -m%n
- logic Operators
- AND,OR,NOT,equal
- Assignment is Right associate
- "="的运算是从右往左,
- ”=“的优先性极低,比关系操作符低
- ”=“,"=="
- 自加,自减
- Adivse: 只在需要的时候采用后缀++,(后缀++需要返回一个拷贝的对象和值,而前缀只返回对象本身)
- 使代码尽量简洁
- The Condition Operate
- cond ? exp1 : exp2;
- Bitwise Operator
- ~,<<,>>,&,^,|
- 建议unsigned定义
- sizeof
chapter 4 Statement
- Null statement
- Null statements should be commented.
- if…else…
- if与临近else匹配
- switch
- while, for, do while
- 在for内定义的变量只在循环内可见
- range for
- If we want to write to the elements in the sequence, the loop variable must be a reference type.
- break, continue
- try…expect…
- throw
- try{/**/}catch{//}
- …