C++笔记(to be cont'd)

最近在看这个:learncpp.com
主要是一些我自己容易忽视的地方
记一些笔记在下面,章节序号对应主页的章节序号,还有错漏地方请不吝赐教

CH1.3a
Rule: Avoid "using" statement outside of a function body.
======

CH1.10
The preprocessor copies the contents of the included file into the including file at the point of the #include directive

Conditional Compilation:
#ifndef SOME_UNIQUE_NAME_HERE
#define SOME_UNIQUE_NAME_HERE
#endif

======
CH2.1
Favor implicit initialization over explicit initialization
int nValue = 5; // explicit initialization
int nValue(5); // implicit initialization

Uniform(list) initialization in C++11
int value{}; // default initialization to 0
int value{4.5}; // error: an integer variable can not hold a non-integer value
If you’re using a C++11 compatible compiler, favor uniform initialization

======
CH2.4
While short int, long int, and long long int are valid, the shorthand versions short, long, and long long should be preferred. In addition to being less typing, adding the prefix int makes the type harder to distinguish from variables of type int. This can lead to mistakes if the short or long modifier is inadvertently missed.
long long int lli; // valid
long long ll; // preferred

All integer variables except char are signed by default. Char can be either signed or unsigned by default (but is usually signed for conformity).
Generally, the signed keyword is not used (since it’s redundant), except on chars (when necessary to ensure they are signed).
Favor signed integers over unsigned integers

======
CH2.4a
<cstdint>:fixed width integers: int8_t/uint8_t/...uint64_t
Until this is clarified by a future draft of C++, you should assume that int8_t and uint8_t may or may not behave like char types.

int can be used when the integer size doesn’t matter and isn’t going to be large.
Fixed-width integers should be used in all other cases.
Only use unsigned types if you have a compelling reason.

======
CH2.5
Summation precision: Kahan summation algorithm
#include <iomanip> // for std::setprecision()

Float values have between 6 and 9 digits of precision, with most float values having at least 7 significant digits. Double values have between 15 and 18 digits of precision, with most double values having at least 16 significant digits. Long double has a minimum precision of 15, 18, or 33 significant digits depending on how many bytes it occupies.
Favor double over float unless space is at a premium, as the lack of precision in a float will often lead to challenges.

Rounding Error matters: 0.1+...+0.1 \neq 1.0. Ref. CH3.5 -- Relational operators

======
CH2.6
ture is evaluated as 1

======
CH2.7
Note that even though cin will let you enter multiple characters, ch will only hold 1 character. Consequently, only the first input character is placed in ch. The rest of the user input is left in the input buffer that cin uses, and can be accessed with subsequent calls to cin.

\n and endl:
Use std::endl when you need to ensure your output is output immediately (e.g. when writing a record to a file, or when updating a progress bar). Note that this may have a performance cost, particularly if writing to the output device is slow (e.g. when writing a file to a disk).
Use ‘\n’ in other cases.

wchar_t should be avoided in almost all cases (except when interfacing with the Windows API). Its size is implementation defined, and is not reliable. It has largely been deprecated.

You won’t need to use char16_t(UTF-16) or char32_t(UTF-32) unless you’re planning on making your program Unicode compatible and you are using 16-bit or 32-bit Unicode characters.

======
CH2.8
0x 16; 0 8; 0b 2(C++14)

======
CH2.9
Making a function parameter const does two things. First, it tells the person calling the function that the function will not change the value of myValue. Second, it ensures that the function doesn’t change the value of myValue.

Any variable that should not change values after initialization should be declared as const (or constexpr in C++11).

Avoid using #define to create symbolic constants, but use const variables to provide a name and context for your magic numbers.

A recommended way:
1) Create a header file to hold these constants
2) Inside this header file, declare a namespace
3) Add all your constants inside the namespace (make sure they’re const)
4) #include the header file wherever you need it
Use the scope resolution operator (::) to access your constants in .cpp files

======
CH3.2
Prior to C++11, if either of the operands of integer division are negative, the compiler is free to round up or down! For example, -5 / 2 can evaluate to either -3 or -2, depending on which way the compiler rounds. However, most modern compilers truncate towards 0 (so -5 / 2 would equal -2). The C++11 specification changed this to explicitly define that integer division should always truncate towards 0 (or put more simply, the fractional component is dropped).

Also prior to C++11, if either operand of the modulus operator is negative, the results of the modulus can be either negative or positive! For example, -5 % 2 can evaluate to either 1 or -1. The C++11 specification tightens this up so that a % b always resolves to the sign of a.

======
CH3.3
Be aware of undefined expressions like:x = x++;
Don’t use a variable that has a side effect( if it modifies some state) applied to it more than once in a given statement.

======
CH3.4
Avoid using the comma operator, except within for loops.
Only use the conditional operator for simple conditionals where it enhances readability.
It’s worth noting that the conditional operator evaluates as an expression, whereas if/else evaluates as statements. This means the conditional operator can be used in some places where if/else can not.
For example, when initializing a const variable:

bool inBigClassroom = false;
const int classSize = inBigClassroom ? 30 : 20;

There’s no satisfactory if/else statement for this, since const variables must be initialized when defined, and the initializer can’t be a statement.

======
CH3.5
Directly comparing floating point values using any of these operators is dangerous. This is because small rounding errors in the floating point operands may cause unexpected results.

Donald Knuth, a famous computer scientist, suggested the following method in his book “The Art of Computer Programming, Volume II: Seminumerical Algorithms (Addison-Wesley, 1969)”:
#include <cmath>

// return true if the difference between a and b is within epsilon percent of the larger of a and b
bool approximatelyEqual(double a, double b, double epsilon)
{
return fabs(a - b) <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}

The author suggests the following approach
// return true if the difference between a and b is less than absEpsilon, or within relEpsilon percent of the larger of a and b
bool approximatelyEqualAbsRel(double a, double b, double absEpsilon, double relEpsilon)
{
// Check if the numbers are really close -- needed when comparing numbers near zero.
double diff = fabs(a - b);
if (diff <= absEpsilon)
return true;

// Otherwise fall back to Knuth‘s algorithm
return diff <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * relEpsilon);
}

Comparison of floating point numbers is a difficult topic, and there’s no “one size fits all” algorithm that works for every case.

======
CH3.6
Any non-zero integer value evaluates to true when used in a boolean context. Mixing integer and boolean operations can be very confusing, and should be avoided!

Short circuit evaluation presents another opportunity to show why operators that cause side effects should not be used.

======
CH3.8
When dealing with bit operators, use unsigned integers.
Note that the results of applying the bitwise shift operators to a signed integer are compiler dependent.

======
CH3.8a
Bit mask and bit flags:
Bit flags are typically used in two cases:
1) When you have many sets of identical bitflags.
2) Set options easily especially there are a lot of options (consider f(arg1,arg2...arg100))

manage bitflags:std::bitset

Bit mask: one application: color channel

======
CH4.1
Note that variables inside nested blocks can have the same name as variable inside outer blocks. When this happens, the nested variable “hides” the outer variable. This is called name hiding or shadowing.

======
CH4.2
By convention, many developers prefix global variable names with “g_” to indicate that they are global. This both helps identify global variables as well as avoids naming conflicts with local variables.

By default, non-const variables declared outside of a block are assumed to be external. However, const variables declared outside of a block are assumed to be internal.

Encapsulate the global variable.

======
CH4.3
Static variables offer some of the benefit of global variables (they don’t get destroyed until the end of the program) while limiting their visibility to block scope. This makes them much safer for use than global variables.

C++笔记(to be cont'd)

时间: 2024-11-05 22:41:01

C++笔记(to be cont'd)的相关文章

使用Java中File类批量创建文件和批量修改文件名

批量创建文件 1 int cont = 1; 2 String s = "E:\\学习资料\\Java笔记-"; 3 while(cont<100){ 4 File f = new File(s+cont+".txt"); 5 if(!f.exists()){ 6 f.createNewFile(); 7 } 8 cont++; 9 } 批量修改文件名 1 File file = new File("E:\\学习资料"); 2 String

PHP学习笔记-文件操作1

转载请标明出处: http://blog.csdn.net/hai_qing_xu_kong/article/details/52294237 本文出自:[顾林海的博客] 前言 PHP支持文件上传功能,因此学习PHP文件的相关操作是必须的,这篇笔记会去记录PHP文件系统的相关知识. 文件打开与关闭 文件处理包括读取.关闭.重写等,例如,访问一个文件需要3步:打开文件.读写文件和关闭文件.其他的操作要么是包含在读写文件中(如显示内容.写入内容等),要么与文件自身的属性有关系(如文件遍历.文件改名等

智能指针_auto_ptr2_学习笔记

//1,release函数只是简单的转移对内存的拥有权,自己变成null,不会delete,一般在将所有权转移给别的智能指针的时候使用.具体可参加源码. 例: #include <memory> #include <iostream> using namespace std; class A { public:  A(int a):m_na(a)  {      cout<<"A cont" <<endl;  }  virtual ~A(

Solr In Action 笔记(3) 之 SolrCloud基础

Solr In Action 笔记(3) 之 SolrCloud基础 在Solr中,一个索引的实例称之为Core,而在SolrCloud中,一个索引的实例称之为Shard:Shard 又分为leader和replica. 1. SolrCloud的特质 作为分布式搜索引擎的SolrCloud具有以下几个特质: 可扩展性 所谓的可扩展性就是指可以通过扩大集群的规模来实现性能的提升.有两种方式来实现可扩展性,一种是纵向扩展,即加快CPU速度,增加RAM,提升磁盘I/O性能等,另一种是横向扩展,就是分

义隆单片机学习笔记之(三) 应用例程

常用寄存器: 0x01 (R1) 计时器 0x02 (R2)程序计数器 PC 0x03 (R3)状态寄存器 0x04 (R4)间址寄存器 0x05 (R5)IO PORT 5 0x06 (R6)IO PORT 6 ----- (IOC5)P5的输入输出配置 ----- (IOC6)P6的输入输出配置 0x0f (ISR,读)中断信号指示寄存器(第三位有效,分别对应于3个中断源) 0x0f (IOCF,写)中断屏蔽标志 0x0E (IOCE)(IO60作为中断输入的配置与看门狗的开关在一个寄存器中

dsp之BF531笔记

获得更多资料欢迎进入我的网站或者 csdn或者博客园 很久以前的BF531的笔记,觉得有用分享出来.摘自于open dsp 通用Gpio ADSP-BF53x 处理器上有16 个PF 接口,这些接口就是通常所有的IO 接口,通过寄存器配置,每一个PF 接口都可以作为外部中断接口. Blackfin 处理器的IO 使用与单片机不同,在使用前必须对该接口进行初始化,如告知接口的方向,如配置为输出接口,则直接配置输出接口电平信号,如配置为输入接口,需打开输入使能开关,配置输出信号触发方式,是否中断触发

map 学习笔记

1.map 常用功能 /**************************************** * File Name: map.cpp * Author: sky0917 * Created Time: 2014年06月 4日 15:49:14 ****************************************/ #include <map> #include <cmath> #include <queue> #include <cstd

前端:jQuery笔记

前端:jQuery笔记 此系列文章乃是学习jQuery的学习笔记. Asp.net MVC Comet推送 摘要: 一.简介 在Asp.net MVC实现的Comet推送的原理很简单. 服务器端:接收到服务器发送的AJAX请求,服务器端并不返回,而是将其Hold住,待到有东西要通知客户端时,才将这个请求返回. 客户端:请求异步Action,当接收到一个返回时,立即又再发送一个. 缺点:会长期占用一个Asp...阅读全文 posted @ 2015-02-10 12:01 逆心 阅读(1072)

【读书笔记】《Node.js入门经典》

Node.js学习笔记 Nodejs学习笔记 Nodejs介绍 npmNode Package Manager 1 npm常用命令 IO的不可预测性 回调 1 回调剖析 2 Node在读写文件使用回调 3 Node在HTTP使用回调 4 回调顺序 5 同步与异步代码 HTTP 1 HTTP响应状态代码 2 使用URL模块响应不同的请求 3 使用Nodejs创建HTTP客户端 4 将函数发布为URL服务提供客户端接口 5 两个js文件相互调用函数 数据持久化 1 将数据写入文件 2 读取环境变量