Cplusplus 简明教程
C++ - Cheat Sheet
此 C programing cheat sheet 可以非常方便地使用,并在短时间内提供关键信息。它专门针对想要了解重要主题并踏入 programming in C 世界的人们量身打造。它包括人们浏览所需的所有主要和次要详细信息,并包含示例和代码片段来指导人们如何实际使用此语言。
This C programing cheat sheet can be very handy to use and provides key information in a short time frame. It is tailormade for people who want to address important topics and leap into the world of programming in C. This includes all major and minor details one might need to surf through, and contains examples and code snippets to guide people on how to practically use this language.
C++ First Program - Hello World
任何编程语言的基础都离不开它的发展过程。任何初学者都会通过学习语法开始学习编程语言。因此,让我们从编写 C++ 中的第一个程序,即 Hello World −
The very foundation of any programming language is the process of it’s development. And any beginner starts to learn a programming language by learning it’s syntax. So, let’s start by writing the very first program in C++, ie. Hello World −
C++ Comments
Comments in C++ 用于编写对程序员有用的额外信息。C 支持单行注释 // 用于指示单行注释,而 /* 用于开始多行注释,而 */ 用于结束多行注释。
Comments in C++ are used to write extra information that are useful to the programmer. C supports single-line comment // is used to indicate the single-line comment, whereas /* is used to start a multi-line comment and */ to end it.
C++ Input and Output Statements
此处,“cin”是输入语句,带有“>>”,而“cout”是输出语句,带有“>>”。
Here, "cin" is the input statement, accompanied by ">>", whereas "cout" is the output statement, accompanied by ">>".
Read also: C++ Basic Input/Output
Read also: C++ Basic Input/Output
C++ Variables
Variables 是存储区域,其中可以始终存储不同类型的数据。c++ 中的变量在使用前必须声明,变量名必须以字母开头,并且可以包含字母、数字和下划线(_)。
Variables are areas of storage where different types of data can be invariably stored. The variables in c++ must be declared before using, and the names of variables must start with an alphabet, and can contain letters, numbers and underscore(_).
C++ Keywords
Keywords 是特定语言的编译器保留的特殊类型的单词,程序员不能显式使用它们。其中一些关键字如下 −
Keywords are special type of words that are reserved by the compiler of a specific language and can’t be explicitly used by the programmer. Some of these keywords are as follows −
asm |
else |
new |
this |
auto |
enum |
operator |
throw |
bool |
explicit |
private |
true |
break |
export |
protected |
try |
case |
extern |
public |
typedef |
catch |
false |
register |
typeid |
char |
float |
reinterpret_cast |
typename |
class |
for |
return |
union |
const |
friend |
short |
unsigned |
const_cast |
goto |
signed |
using |
continue |
if |
sizeof |
virtual |
default |
inline |
static |
void |
delete |
int |
static_cast |
volatile |
do |
long |
struct |
wchar_t |
double |
mutable |
switch |
while |
dynamic_cast |
namespace |
template |
C++ Data Types
Data types 是变量在内存中存储的位置的可用分类。数据类型可以分为三个部分 −
Data types are types of available classifications of storage where variables are stored in the memory. Data types can be categorized into three sections −
1. Primitive data types
基本数据类型已经存在 c++ language libraries. 中。可以使用这些数据类型,而无需进行任何修改。
Primitive data types are already existing in the c++ language libraries. These can be used without any modification.
用于整数数据类型的关键字是 int。整数通常需要 4 字节的内存空间,范围从 -2147483648 到 2147483647。
The keyword used for integer data types is int. Integers typically require 4 bytes of memory space and range from -2147483648 to 2147483647.
浮点数据类型用于存储单精度浮点值或十进制值。用于浮点数据类型的关键字是 float。float 变量通常需要 4 字节的内存空间。
Floating Point data type is used for storing single-precision floating-point values or decimal values. The keyword used for the floating-point data type is float. Float variables typically require 4 bytes of memory space.
Character data type 用于存储字符。用于字符数据类型的关键字是 char。字符通常需要 1 字节的内存空间,范围从 -128 到 127 或 0 到 255。
Character data type is used for storing characters. The keyword used for the character data type is char. Characters typically require 1 byte of memory space and range from -128 to 127 or 0 to 255.
双浮点数据类型用于存储双精度浮点值或十进制值。用于双浮点数据类型的关键字是 double。
Double Floating Point data type is used for storing double-precision floating-point values or decimal values. The keyword used for the double floating-point data type is double.
字符串数据类型用于将多个字符存储在单个变量中。
String data type is used for storing multiple characters together in a single variable.
Boolean data type 用于存储布尔值或逻辑值。布尔变量可以存储 true 或 false。用于布尔数据类型的关键字是 bool。
Boolean data type is used for storing Boolean or logical values. A Boolean variable can store either true or false. The keyword used for the Boolean data type is bool.
int main() {
int age=12;
//takes only whole numbers, size is 4 Bytes
float weight=70.4;
//takes decimal valued numbers, size is 4 Bytes
char alpha='a';
//takes single characters as per ASCII, size is 1 Bytes
string s="hey siri";
//takes multiple characters, size is variable
double d=2.2222;
//takes more precise floating point numbers, size is 8 Bytes
bool k=true;
//takes only true or false values (or 0/1)
return 0;
}
2. Derived data types
这些类型是从基元数据类型衍生的,被称为衍生数据类型。它们可以有以下四种类型:
These are derived from the primitive datatypes , and are referred to as Derived Data Types. These can be of four types namely −
这些类型将在后续部分中进行简要讨论。
These are briefly discussed in the further sections.
3. User-defined data types
这些数据类型是由用户自己定义的,并且可以根据用户希望进行自定义。主要有五种类型:
These datatypes are defined by the user itself, and can be customized as per the user’s wish. These are of five types mainly −
本备忘单的 OOPS 部分介绍了类和对象的概念。这里可以参阅示例。
The concept of classes and objects is explained in OOPS section of this cheatsheet. Examples can be referred here.
#include <bits/stdc++.h>
using namespace std;
class MyClass {
public:
int myNum;
string myString;
};
int main() {
MyClass myObj;
myObj.myNum = 1234567;
myObj.myString = "Helloooo";
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
1234567
Helloooo
结构的定义语法如下。
The syntax of defining a structure is as follows.
struct structName{
char varName[size];
int varName;
};
联合的定义语法如下。
The syntax of defining a union is as follows.
Union_Name{
// Declaration of data members
}; union_variables;
枚举变量的定义语法如下。
The syntax of defining an enum variable is as follows.
enum nameOfEnum {
varName1 = 1, varName2 = 0
};
类型定义的定义语法如下。
The syntax of defining a typedef is as follows.
typedef typeName;
#include <bits/stdc++.h>
using namespace std;
typedef unsigned char BYTE;
int main() {
BYTE b1, b2;
b1 = 'c';
cout << " " << b1;
return 0;
}
c
C++ Conditional Statements
Conditional statements 控制程序流程,并且当我们需要定义不同的情况和条件时可以使用。在这种情况下,使用基元“if”、“else”、“else if”、“switch”和三元运算符。
Conditional statements control the flow of the program, and can be used when we need to define different cases and conditions. The primitives "if", "else", "else if", "switch" and the ternary operator are used in such cases.
-
if Statement
-
if-else Statement
-
if-else-if Statement
-
Nested if-else Statement
-
Switch Statement
-
Ternary Operator
1. If statement
如果且仅当给定的条件为真时,if 语句执行代码块。
If statement executes a block of code if and only if the given condition is true.
2. if-else Statement
如果 if 语句内的条件为真,则执行 if 块内的代码,否则执行 else 块内的代码。
If the condition inside the if statement is true, then the code inside the if block will get executed, otherwise code inside the else block will get executed.
3. if-else-if Statement
else if 语句允许您按顺序检查多个条件。
The else if statement allows you to check for multiple conditions sequentially.
4. Nested if Statements
可以将多个 if 语句嵌套在彼此内部,以根据要求形成不同的情况。
Multiple if statements can be nested inside each other to form different cases as per requirement.
5. Ternary Operator
它作为一个条件语句,该语句采用条件语句并返回第一条语句或第二条语句。
It works as a conditional statement which takes a conditional statement and returns either the first statement or the second statement.
6. Switch Case
对于多条件,我们可以简单地使用 switch case 语句以便于处理此类条件。
In case of multiple conditions, we can simply use switch case statements to make it easier to handle such conditions.
Example
#include <iostream>
using namespace std;
int main() {
//program to explain if, else if and else conditions
int age=12;
if(age<12) cout<<"YES"<<endl;
else if(age>24) cout<<"NO"<<endl;
else cout<<"MAYBE"<<endl;
//program to explain ternary operator
bool x=true;
x==1 ? cout<<"true"<<endl : cout<<"false"<<endl;
//program to explain switch case with break and default
switch (x & x){
case 0 :
cout<<"false"<<endl;
break;
case 1 :
cout<<"true"<<endl;
break;
default:
cout<<"invalid"<<endl;
break;
}
return 0;
}
MAYBE
true
true
C++ Operators
Operators in C++ 可以分为 6 种类型:
Operators in C++ can be classified into 6 types −
1. Arithmetic Operators
这些运算符用于对操作数执行算术或数学运算。例如,‘+’用于加法,‘-’用于减法,‘*’用于乘法等。
These operators are used to perform arithmetic or mathematical operations on the operands. For example, ‘+’ is used for addition, ‘-‘ is used for subtraction ‘*’ is used for multiplication, etc.
#include <iostream>
using namespace std;
int main() {
int a = 8, b = 3;
// Addition operator
cout << "a + b = " << (a + b) << endl;
// Subtraction operator
cout << "a - b = " << (a - b) << endl;
// Multiplication operator
cout << "a * b = " << (a * b) << endl;
// Division operator
cout << "a / b = " << (a / b) << endl;
// Modulo operator
cout << "a % b = " << (a % b) << endl;
//unary operators
a++;
cout<<a<<endl;
a--;
cout<<a<<endl;
int k=++a + ++b;
cout<<k<<endl;
k=++a - --b;
cout<<k<<endl;
return 0;
}
a + b = 11
a - b = 5
a * b = 24
a / b = 2
a % b = 2
9
8
13
7
2. Relational Operators
这些运算符用于比较两个操作数的值。例如,‘>’检查一个操作数是否大于另一个操作数等。结果返回布尔值,即 true 或 false。
These operators are used for the comparison of the values of two operands. For example, ‘>’ checks if one operand is greater than the other operand or not, etc. The result returns a Boolean value, i.e., true or false.
#include <iostream>
using namespace std;
int main() {
int a = 6, b = 4;
// Equal to operator
cout << "a == b is " << (a == b) << endl;
// Greater than operator
cout << "a > b is " << (a > b) << endl;
// Greater than or Equal to operator
cout << "a >= b is " << (a >= b) << endl;
// Lesser than operator
cout << "a < b is " << (a < b) << endl;
// Lesser than or Equal to operator
cout << "a <= b is " << (a <= b) << endl;
// true
cout << "a != b is " << (a != b) << endl;
return 0;
}
a == b is 0
a > b is 1
a >= b is 1
a < b is 0
a <= b is 0
a != b is 1
3. Logical Operators
这些运算符用于合并两个或更多的条件或约束,或补充对所考虑的原始条件的求值。结果返回布尔值,即 true 或 false。
These operators are used to combine two or more conditions or constraints, or to complement the evaluation of the original condition in consideration. The result returns a Boolean value, i.e., true or false.
#include <iostream>
using namespace std;
int main() {
int a = 6, b = 4;
// Logical AND operator
cout << "a && b is " << (a && b) << endl;
// Logical OR operator
cout << "a || b is " << (a || b) << endl;
// Logical NOT operator
cout << "!b is " << (!b) << endl;
return 0;
}
a && b is 1
a || b is 1
!b is 0
4. Bitwise Operators
这些运算符用于对操作数执行位级运算。首先将运算符转换为位级,然后对操作数执行运算。加法、减法、乘法等数学运算可以在位级别执行,以进行更快的处理。
These operators are used to perform bit-level operations on the operands. The operators are first converted to bit-level and then the calculation is performed on the operands. Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at the bit level for faster processing.
#include <iostream>
using namespace std;
int main() {
int a = 6, b = 4;
// Binary AND operator
cout << "a & b is " << (a & b) << endl;
// Binary OR operator
cout << "a | b is " << (a | b) << endl;
// Binary XOR operator
cout << "a ^ b is " << (a ^ b) << endl;
// Left Shift operator
cout << "a<<1 is " << (a << 1) << endl;
// Right Shift operator
cout << "a>>1 is " << (a >> 1) << endl;
// One’s Complement operator
cout << "~(a) is " << ~(a) << endl;
return 0;
}
a & b is 4
a | b is 6
a ^ b is 2
a<<1 is 12
a>>1 is 3
~(a) is -7
5. Assignment Operators
这些运算符用于向变量赋值。赋值运算符的左侧操作数是变量,右侧操作数是值。右侧的值必须与左侧的变量具有相同的数据类型,否则编译器会引发错误。
These operators are used to assign value to a variable. The left side operand of the assignment operator is a variable and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type as the variable on the left side otherwise the compiler will raise an error.
#include <iostream>
using namespace std;
int main() {
int a = 6, b = 4;
// Assignment Operator
cout << "a = " << a << endl;
// Add and Assignment Operator
cout << "a += b is " << (a += b) << endl;
// Subtract and Assignment Operator
cout << "a -= b is " << (a -= b) << endl;
// Multiply and Assignment Operator
cout << "a *= b is " << (a *= b) << endl;
// Divide and Assignment Operator
cout << "a /= b is " << (a /= b) << endl;
return 0;
}
a = 6
a += b is 10
a -= b is 6
a *= b is 24
a /= b is 6
C++ Loops
Looping statements 用于以连续方式遍历某些数据。循环在 data structures (如 arrays 、链表、图、树等)中得到广泛使用。它们是高级概念(如递归、动态规划和图论)的构建模块。主要有三种类型的循环语句 −
Looping statements are used to traverse through some data in a contiguous manner. Loops are used extensively in data structures like arrays, linked lists, graphs, trees and so on. These are the building blocks of concepts like recursion, dynamic programming and graph theory, which are advanced concepts. There are mainly three types of looping statements −
1. For loop
For 循环用于在结束条件下结束循环之前遍历特定数据结构一定次数。
For loops are used to travel a certain data stucture for a specific number of times before ending the loop at an ending condition.
#include <iostream>
using namespace std;
int main() {
for(int i=0;i<6;i++){
cout<<"hello"<<endl;
}
return 0;
}
hello
hello
hello
hello
hello
hello
2. While loop
While 循环用于运行循环语句,直至指定条件变为假,否则循环将连续运行。
While loops are used to run a looping statement until the specified condition turns false, otherwise the loops runs continuously.
#include <bits/stdc++.h>
using namespace std;
int main() {
int i=0;
while(i<6){
cout<<"hello"<<endl;
i++;
}
return 0;
}
hello
hello
hello
hello
hello
hello
3. Do-while loop
在 do-while 循环中,循环首次在给定条件下运行,然后检查 while 语句以进一步运行。
In do-while loops, the loop runs the first time on a given condition and then checks the while statement to run further.
#include <bits/stdc++.h>
using namespace std;
int main() {
int i=0;
do{
cout<<"hello"<<endl;
i++;
}while(i<6);
return 0;
}
hello
hello
hello
hello
hello
hello
C++ References and Pointers
References 和 pointers 用于描述用户声明的变量的位置和面值。
References and pointers are used to describe the place and the face value of the variable declared by the user.
1. References
引用用于为同一内存位置和其中存储的值创建新名称。我们可以在变量名的旁边使用安培符 ($) 符号来创建对任何变量的引用。
References are used to create a new name for the same memory location and the value stored there. We can create reference to any variable using ampersand($) symbol next to the variable name.
#include <bits/stdc++.h>
using namespace std;
int main() {
int i=3;
int &k=i;
cout<<i<<k<<endl;
return 0;
}
33
2. Pointers
Pointers 是用于存储它们所指向变量的地址的变量,而 * 用于声明指向任何变量的指针。
Pointers are variables that are used to store the address of the variable that they point to, and the * is used to declare a pointer to any variable.
#include <bits/stdc++.h>
using namespace std;
int main() {
int a=4;
int *ptr=&a;
cout<<a<<ptr<<*ptr<<endl;
return 0;
}
40x7ffeb2bcfb0c4
C++ Arrays
array 是相同数据类型的元素的序列,它们存储在存储中的连续内存位置中。该数组可以在有或没有元素数的情况下声明。
An array is a sequence of elements of same data type that are stored in contiguous memory locations in the storage. The array can be declared with and without the number of elements.
Example
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr1[]={1,2,3,4,4,3,2,1};
int arr2[8]={0};
for(int i=0;i<8;i++){
cout<<arr1[i]<<arr2[i]<<endl;
}
return 0;
}
10
20
30
40
40
30
20
10
Multidimensional Arrays
数组也可以以多个维度定义,所有元素都具有相同的数据类型。
Arrays can also be defined in more than one dimensions, with all elements of the same datatype.
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[2][3]={{1,2,3},{4,4,3}};
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
cout<<arr[i][j]<<endl;
}
}
return 0;
}
1
2
3
4
4
3
C++ Functions
Functions 是代码的一部分,如果先前已定义,则可以调用,并且有助于使代码简洁且可读。函数可以作为程序的一部分或作为类主体来创建。 compiler in c++ 执行的第一个函数为主函数。
Functions are parts of the code that can be called if defined previously, and help to make the code concise and readable. Functions can be created as part of the program or in the class body as well. The first function executed by the compiler in c++ is the main function.
该函数具有名称、返回类型(也可以是 void)、输入变量和方法主体。下面的示例展示了如何在 c++ 中定义和使用函数。
The function has a name, a return type (which can also be void), input variables and a method body. The example below showcases how functions are defined and used in c++.
c++ 中的函数可以分为两类 −
Functions in c++ can be of two types −
-
Primitive Functions which are already defined in the c++ library. Examples of primitive functions are math functions like sin(), cos(), min(), max() and so on.
-
User Defined Functions, which are defined as per the requirement of the user and can be customized accordingly.
C++ Math Functions
C 作为 C 的超集,支持大量有用的 mathematical functions. 。这些函数在标准 C 中可用,以支持各种数学运算。
C being a superset of C, supports a large number of useful mathematical functions. These functions are available in standard C to support various mathematical calculations.
这些函数无需重点关注实现,可以直接用于简化代码和程序。为了使用这些函数,需要包含头文件 − <math.h> 或 <cmath>。
Instead of focusing on implementation, these functions can be directly used to simplify code and programs. In order to use these functions you need to include a header file − <math.h> or <cmath>.
下面的示例显示了可以使用哪些数学函数,这些函数可以直接用于复杂计算。
The below example shows the use of many such math functions that can be directly used instead of complex calculations.
Example
#include <bits/stdc++.h>
using namespace std;
int main() {
double x = 2.3;
cout << "Sine value of x=2.3 : " << sin(x) << endl;
cout << "Cosine value of x=2.3 : " << cos(x) << endl;
cout << "Tangent value of x=2.3 : " << tan(x) << endl;
double y = 0.25;
cout << "Square root value of y=0.25 : " << sqrt(y)
<< endl;
int z = -10;
cout << "Absolute value of z=-10 : " << abs(z) << endl;
cout << "Power value: x^y = (2.3^0.25) : " << pow(x, y)
<< endl;
x = 3.0;
y = 4.0;
cout << "Hypotenuse having other two sides as x=3.0 and"
<< " y=4.0 : " << hypot(x, y) << endl;
x = 4.56;
cout << "Floor value of x=4.56 is : " << floor(x)
<< endl;
x = -4.57;
cout << "Absolute value of x=-4.57 is : " << fabs(x)
<< endl;
x = 1.0;
cout << "Arc Cosine value of x=1.0 : " << acos(x)
<< endl;
cout << "Arc Sine value of x=1.0 : " << asin(x) << endl;
cout << "Arc Tangent value of x=1.0 : " << atan(x)
<< endl;
y = 12.3;
cout << "Ceiling value of y=12.3 : " << ceil(y) << endl;
x = 57.3; // in radians
cout << "Hyperbolic Cosine of x=57.3 : " << cosh(x)
<< endl;
cout << "Hyperbolic tangent of x=57.3 : " << tanh(x)
<< endl;
y = 100.0;
// Natural base with 'e'
cout << "Log value of y=100.0 is : " << log(y) << endl;
return 0;
}
Sine value of x=2.3 : 0.745705
Cosine value of x=2.3 : -0.666276
Tangent value of x=2.3 : -1.11921
Square root value of y=0.25 : 0.5
Absolute value of z=-10 : 10
Power value: x^y = (2.3^0.25) : 1.23149
Hypotenuse having other two sides as x=3.0 and y=4.0 : 5
Floor value of x=4.56 is : 4
Absolute value of x=-4.57 is : 4.57
Arc Cosine value of x=1.0 : 0
Arc Sine value of x=1.0 : 1.5708
Arc Tangent value of x=1.0 : 0.785398
Ceiling value of y=12.3 : 13
Hyperbolic Cosine of x=57.3 : 3.83746e+24
Hyperbolic tangent of x=57.3 : 1
Log value of y=100.0 is : 4.60517
C++ Object-Oriented Programming
OOPS concepts 在 C++ 中也可以存在。这基本上意味着程序可以细分为类和对象。
OOPS concepts exist in C++ as well. This basically means the program can be subcategorized into classes and objects.
1. Class
一个类是一种用户定义的数据类型,它包含两个组成部分,变量和方法。可以使用 constructor. 初始化该类
A class is a user-defined data type that has two components, the variables and the methods. The class can be initialized using a constructor.
2. Objects
一个对象就是类的实例或变量。对象在存储空间内占用内存。
An object is an instance or a variable of the class. Objects occupy memory in the storage space.
3. Encapsulation
封装是将数据和方法一起包装在单个类或类别下。为此,使用了类。
Encapsulation is wrapping up the data and methods together under a single class or category. For this, classes are used.
5. Polymorphism
使用相同的名称和主体创建对象的多个实例或方法称为多态性。
Using same name and body to create multiple instances of an object or method is known as polymorphism.
多态性有以下类型:
There are types of polymorphism:
编译时多态性可以使用 − 实现
Compile-time Polymorphism can be achieved using −
运行时多态性可以使用 − 实现
Runtime Polymorphism can be achieved using −
-
Viral Functions
C++ File Handling
文件处理中的不同操作如下 −
The different operations in file handling are as follows −
-
Open file − To open a file, use the open() method of the ofstream class.
-
Read a file − To read a file, use the getline() method of the ifstream class.
-
Write a file − Use the "<<" operator to write on a file while it is opened.
Example
#include <bits/stdc++.h>
using namespace std;
int main(){
ofstream outputFile("file1.txt");
// Open the file for writing
outputFile.open("file1.txt");
if (outputFile.is_open()) {
// Write data to the file
outputFile << "Hello, World!" << endl;
outputFile << 1333113 << endl;
outputFile.close(); // Close the file
}else {
// Failed to open the file
cout << "Error"<< endl;
return 1;
}
// Reading from a file
ifstream inputFile("file1.txt");
if (inputFile.is_open()) {
string line;
while (getline(inputFile, line)) {
// Print each line
cout << line << endl;
}
// Close the file
inputFile.close();
}else {
// Failed to open the file
cout << "Error"<< endl;
return 1;
}
return 0;
}
C++ Exception Handling
在使用类和对象时,由于用户编写的程序存在某些错误或由于机器错误(如内存或执行),可能出现各种 errors and exceptions 。这些错误可能会对程序的顺利执行造成破坏,因此需要使用 try 和 catch 块来处理这些错误。
When working with classes and objects, various errors and exceptions are possible due to some fault either in the program written by the user or due to some machine fault, like memory or execution. These errors may be fatal to the smooth execution of a program, and hence need to be handled using try and catch blocks.
当出现错误时,C 语言通常会停止并生成一条错误消息。这个术语的专业术语是:C 将抛出一个异常(抛出一个错误)。
When an error occurs, C will normally stop and generate an error message. The technical term for this is: C will throw an exception (throw an error).
-
Try Block − The try statement allows you to define a block of code to be tested for errors while it is being executed.
-
Throw − The throw keyword throws an exception when a problem is detected, which lets us create a custom error.
-
Catch Block − The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
C++ Preprocessor
预处理器是一些关键字,在编译器开始实际编译之前,它们会向编译器发出指示来处理这些指令。这些指令以“#”开头,并且不需要以“;”结尾,因为它们不是语句。
The preprocessors are keywords that give directions to the compiler to process the instructions before the actual compilation starts. These begin with a ‘#’, and do not need any ‘;’ at the end as these are not statements.
预处理器的例子包括 #include、#define 等很多内容。
Examples of preprocessors are #include, #define and many more.
让我们来看看 C++ 库中的重要预处理器 −
Let us look at the important preprocessors in C++ library −
-
#include
-
#define
1.
它用于包含头文件和库,这些头文件和库对于执行程序中使用的函数和方法是必需的。如前文所述,方法的实际实现没有显示出来,只显示最终结果。
It is used to include header files and libraries that are required to execute the methods and functions used in the program. As stated earlier, the actual implementation of the method is not shown, and the end result is displayed.
#include <math.h>
#include <iostream>
using namespace std;
//the iostream is used for input and output stream of data
//the math.h is used for including math functions like pow(x,y)
int main(void){
cout<<pow(2,3);
return 0;
}
8
2.
define preprocessor directive creates symbolic constants. The symbolic constant is called a macro and the general form of the directive is the symbol ‘ ’ 后跟 define 语句,以及需要定义的常量的定义。当这一格式出现在文件中时,在编译程序之前,文件中所有后续出现的宏都将被 replacement-text 替换。
The define preprocessor directive creates symbolic constants. The symbolic constant is called a macro and the general form of the directive is the symbol ‘’ followed by define statement and the definition of the constant that needs to be defined. When this format appears in a file, all subsequent occurrences of macro in that file will be replaced by replacement-text before the program is compiled.
#include <bits/stdc++.h>
using namespace std;
#define A 45
//defining value of A as 45
int main(void){
int a= A;
cout<<a;
return 0;
}
45
C++ Namespaces
命名空间用于在一个程序中定义名称相同的两个函数。这样一来,当调用函数时,编译器就会知道使用哪个方法。通过使用命名空间,你可以定义名称的定义上下文。本质上,一个命名空间定义一个范围。
A namespace is used to define two functions of the same name in a program. This way, the compiler knows which method to use when calling calling a function. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.
定义命名空间是一件很容易的事情。你可以编写一个命名空间,然后在方法内编写代码。可以通过键入来自该命名空间的命名空间,外加介于其中的 '::' 符号,在程序中使用这一函数。
Defining a namespace is easy. You can just write namespace followed by the code inside the method. This function can be used inside a program by mentioning the namespace where it is from, along with ‘::’ symbol in between.
Example 1
#include <bits/stdc++.h>
using namespace std;
// first name space
namespace first_space {
void func() {
cout << "Inside first_space" << endl;
}
}
// second name space
namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}
int main () {
// Calls function from first name space.
first_space::func();
// Calls function from second name space.
second_space::func();
return 0;
}
Inside first_space
Inside second_space
using 关键字可以以指令的形式使用,用于引导后面的代码遵守已提到的命名空间。'std' 关键字的用法与此类似,用于提到全部代码都将遵守标准命名空间。
The using keyword can be used in form of a directive to direct the following code to adhere to the mentioned namespace. The ‘std’ keyword is similarly used to mention that all of the code is going to adhere to the standard namespace.
要了解关于命名空间的更多内容,请参阅这篇文章 – Namespaces in C++
To know more about namespaces, refer to this article – Namespaces in C++
Example 2
#include <bits/stdc++.h>
using namespace std;
// first name space
namespace first_space {
void func() {
cout << "Inside first_space" << endl;
}
}
// second name space
namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}
using namespace first_space;
int main () {
// Calls function from first name space.
func();
return 0;
}
Inside first_space
C++ Templates
A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms have been developed using template concept.
C++ 中提供两种模板类型 −
There are two types of templates available in C++ −
-
Class Template
-
Function Template
1. Class Template
类模板可用于定义不同的数据结构,例如,链表、堆栈、队列、优先队列、树等等。类模板可以通过以下方式定义 −
Class templates can be used to define different data structures like linked lists, stack, queue, priority queue, tree and so on. Class template can be defined in the following way −
template <class type> class class-name {
.
.
.
}
#include <bits/stdc++.h>
using namespace std;
template <typename T> class Array {
T* pointer;
int size;
public:
Array(T a[], int s);
void show();
};
template <typename T> Array<T>::Array(T a[], int s){
pointer = new T[s];
size = s;
for (int i = 0; i < size; i++)
pointer[i] = a[i];
}
template <typename T> void Array<T>::show(){
for (int i = 0; i < size; i++)
cout << *(pointer + i)<<endl;
cout << endl;
}
int main(){
int size=7;
int a[size] = { 12, 21, 45, 34, 19, 55, 66 };
Array<int> a1(a, 7);
a1.show();
return 0;
}
12
21
45
34
19
55
66
2. Function Template
这些可用于创建泛型函数,使用具有内置功能的模板库。max()、min()、sin()、floor() 等都是函数模板的一些例子。
These can be used to create generic functions using template libraries, with inbuilt functionalities. Some examples of function templates are max(), min(), sin(), floor(), etc.
#include <bits/stdc++.h>
using namespace std;
template <typename T> T minof3(T x, T y, T z){
if(x<y && x<z) return x;
if(y<x && y<z) return y;
if(z<x && z<y) return z;
// else return "Not applicable !!!";
}
int main(){
// Call minof3 for int
cout << minof3<int>(32,58,97) << endl;
// call minof3 for double
cout << minof3<double>(13.0,12.0, 17.0) << endl;
// call minof3 for char
cout << minof3<char>('g', 'e', 't') << endl;
// call minof3 for string
cout << minof3<string>("apple", "ball", "cat")<<endl;
return 0;
}
32
12
e
apple
C++ Dynamic Memory
C++ 中的内存分为两个部分 −
Memory in C++ is divided into 2 parts −
-
Stack Memory − All variables declared inside the function will take up memory from the stack.
-
Heap Memory − This is unused memory of the program and can be used to allocate the memory dynamically when program runs.
在你编写程序时,有时可能会出现一个情况,所需的内存事先未知,因此运行时就需要堆内存中的额外空间。这是动态内存分配,这可以通过使用 'new' 关键字来实现。利用这个空间后,可以使用 'delete' 关键字取消分配数据。
When you write a program, sometimes it might occur that the memory required would not be known beforehand, and hence extra space from the heap memory would be required at runtime. This is dynamic memory allocation, and this can be implemented using the ‘new’ keyword. After utilizing this space, the data can be deallocated using the ‘delete’ keyword.
C 中的 malloc() 函数在 C 中仍然存在,但建议避免使用 malloc() 函数。new 相较于 malloc() 的主要优势在于 new 并不只是分配内存,它还会构造对象,这是 C 的主要目的。
The malloc() function from C, still exists in C, but it is recommended to avoid using malloc() function. The main advantage of new over malloc() is that new doesn’t just allocate memory, it constructs objects which is prime purpose of C.
Example
#include <bits/stdc++.h>
using namespace std;
int main () {
int *ptr = NULL; // Pointer initialized with null
ptr = new int; // Request memory for the variable
*ptr = 31; // Store value at allocated address
cout << "Value of pointer : " << *ptr << endl;
delete ptr; // free up the memory.
return 0;
}
Value of pointer : 31
类似地,在实现数组和类时也可以分配动态内存。要获得有关动态内存分配的更多信息,请参阅这篇关于动态内存分配的文章。
Similarly, dynamic memory can be allocated while implementing arrays and classes as well. For any more information regarding Dynamic Memory allocation- refer to this article on Dyamic Memory Allocation.
C++ Signal Handling
信号处理是控制在程序执行期间传递的中断信号的过程。各种中断可以过早地结束程序并生成不同的响应。例如,在 Linux/Unix 命令行界面 (CLI) 中,“CTRL+C”命令生成结束程序中断。同样地,C++ 编程语言中也存在许多中断。这些中断在 <csignal> 库中定义。
Signal handling is the process of controlling interrupt signals delivered during the execution of the program. There are various kinds of interrupts, which can prematurely end the program and generate different responses. For example, in Linux/Unix command line interface (CLI) the ‘CTRL+C’ command generate the end program interrupt. Similarly, there exist many interrupts in C++ programming language as well. These are defined in the <csignal> library.
Sr.No |
Signal & Description |
1 |
SIGABRT Abnormal termination of the program, such as a call to abort. |
2 |
SIGFPE An erroneous arithmetic operation, such as a divide by zero or an operation resulting in overflow. |
3 |
SIGILL Detection of an illegal instruction. |
4 |
SIGINT Receipt of an interactive attention signal. |
5 |
SIGSEGV An invalid access to storage. |
6 |
SIGTERM A termination request sent to the program. |
1. signal() Function
信号函数由 <csignal> 库提供,用于立即捕获不需要或错误的中断。下面是 signal() 函数的用法,该函数接受两个输入,第一个是信号号,第二个是信号处理函数。
The signal function is provided by the <csignal> library, and is used to trap unwanted or bad interrupts at once. Here is the usage of signal() function, which takes two inputs, first one is the signal number, and the second is the signal handling function.
#include <csignal>
#include <iostream>
using namespace std;
void handler_func(int signal_num){
cout << endl<<"You have interrupted: (" << signal_num
<< "). \n";
//using exit to terminate
exit(signal_num);
}
int main(){
//initialize signal
signal(SIGABRT, handler_func);
while (true) {
cout << "You can't stop me !!!" << endl;
this_thread::sleep_for(chrono::seconds(1));
//this is used for delay
}
return 0;
//press ctrl+c to interrupt the program execution!!!
}
2. raise() Function
信号函数由 <csignal> 库提供,用于生成带有其号的中断。下面是 raise() 函数的用法,该函数接受一个输入,即信号号。
The signal function is provided by the <csignal> library, and is used generate interrupts with their numbers. Here is the usage of raise() function, which takes onw input which is the signal number.
#include <csignal>
#include <iostream>
using namespace std;
void signal_handler(int signum){
cout << "You generated this interrupt: (" << signum << ").\n";
// terminate program
exit(signum);
}
int main(){
int i = 0;
signal(SIGABRT, signal_handler);
while (++i) {
cout << "You can't stop me !!!" << endl;
if (i == 10)
raise(SIGABRT);
}
return 0;
}
C++ Multithreading
多线程是处理器上操作系统概念中的多任务处理的一部分。多任务处理通常分为基于进程和基于线程两部分。
Multithreading is part of the operating systems concept of multitasking on a processor. Multitasking is generally subcategorized into two parts- Process based and Thread based.
在基于进程的多任务处理中,两个或更多进程或程序在处理器上并发运行同时执行,并且完全依赖于处理器处理任务的能力。
In process based multitasking, two or more processes or programs run concurrently on a processor while executing, and it is completely dependent on the prowess of the processor to handle the tasks.
在基于线程的多任务处理中,每个程序被划分为线程,可以将这些线程视为在处理器上并发运行并一起生成响应的较小子程序。因此,多个线程结合在一起成为一个程序。这称为多线程。
In thread based multitasking, each program is divided into threads, which can be thought of as smaller subprograms that concurrently run on a processor and generate response together. Hence, multiple threads combine together to become a single program. This is known as Multithreading.
在 C 语言中,在推出 C 11 之前没有内置的多线程支持。C++ 使用 POSIX 线程,或在许多类 Unix 的 POSIX 系统上可用的 Pthreads。可在 pthreads 上执行以下操作:
In C, there was no built-in support of multithreading before the launch of C 11. C++ uses POSIX Threads, or Pthreads which are available on many Unix-like POSIX systems. The following operations can be performed on pthreads −
-
Creating threads
-
Terminating threads
-
Passing arguments to threads
-
Joining and detaching threads
Creating threads
可以在 <pthread.h> 库中使用例程 pthread_create 创建线程。可以在程序中的任何位置创建这些线程。
Threads can be created using the routine pthread_create, in the <pthread.h> library. These can be created anywhere inside the program.
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg);
Sr.No |
Parameter & Description |
1 |
thread An opaque, unique identifier for the new thread returned by the subroutine. |
2 |
attr An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values. |
3 |
start_routine The C++ routine that the thread will execute once it is created. |
4 |
arg A single argument that may be passed to start_routine. It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed. |
Terminating a thread
pthread_exit() 用于终止线程,当线程完成执行并且在程序中不再需要时使用。这有助于清除最初分配给线程的空间。
The pthread_exit() is used to terminate a thread after it has completed its execution and is no longer required in the program. This helps clear the space assigned to the thread in the first place.
#include <pthread.h>
pthread_exit (status);
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
void *PrintHello(void *threadid) {
long tid;
tid = (long)threadid;
cout << "Hello World! Thread ID, " << tid << endl;
pthread_exit(NULL);
}
int main () {
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i = 0; i < NUM_THREADS; i++ ) {
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
if (rc) {
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
main() : creating thread, 0
main() : creating thread, 1
Hello World! Thread ID, 0
main() : creating thread, 2
Hello World! Thread ID, 1
main() : creating thread, 3
Hello World! Thread ID, 2
main() : creating thread, 4
Hello World! Thread ID, 3
Hello World! Thread ID, 4
Joining and detaching threads
以下惯例用于加入和分离程序中的线程 −
The following routine is used to join and detatch threads in a program −
pthread_join (threadid, status)
pthread_detach (threadid)
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
using namespace std;
#define NUM_THREADS 5
void *wait(void *t) {
int i;
long tid;
tid = (long)t;
sleep(1);
cout << "Sleeping in thread " << endl;
cout << "Thread with id : " << tid << " ...exiting " << endl;
pthread_exit(NULL);
}
int main () {
int rc;
int i;
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
void *status;
// Initialize and set thread joinable
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for( i = 0; i < NUM_THREADS; i++ ) {
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], &attr, wait, (void *)i );
if (rc) {
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
// free attribute and wait for the other threads
pthread_attr_destroy(&attr);
for( i = 0; i < NUM_THREADS; i++ ) {
rc = pthread_join(threads[i], &status);
if (rc) {
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
cout << "Main: completed thread id :" << i ;
cout << " exiting with status :" << status << endl;
}
cout << "Main: program exiting." << endl;
pthread_exit(NULL);
}
main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Sleeping in thread
Thread with id : 0 ...exiting
Sleeping in thread
Thread with id : 2 ...exiting
Sleeping in thread
Thread with id : 1 ...exiting
Main: completed thread id :0 exiting with status :0
Sleeping in thread Main: completed thread id :1 exiting with status :0
Main: completed thread id :2 exiting with status :0
Thread with id : 4 ...exiting
Sleeping in thread
Thread with id : 3 ...exiting
Main: completed thread id :3 exiting with status :0
Main: completed thread id :4 exiting with status :0
Main: program exiting.
Passing arguments to threads
以下程序演示如何使用多线程在线程内传递参数和语句。
The following program demonstrates how to pass arguments and statements inside threads using multithreading.
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
struct thread_data {
int thread_id;
char *message;
};
void *PrintHello(void *threadarg) {
struct thread_data *my_data;
my_data = (struct thread_data *) threadarg;
cout << "Thread ID : " << my_data->thread_id ;
cout << " Message : " << my_data->message << endl;
pthread_exit(NULL);
}
int main () {
pthread_t threads[NUM_THREADS];
struct thread_data td[NUM_THREADS];
int rc;
int i;
for( i = 0; i < NUM_THREADS; i++ ) {
cout <<"main() : creating thread, " << i << endl;
td[i].thread_id = i;
td[i].message = "This is message";
rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]);
if (rc) {
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
Thread ID : 0 Message : This is message
Thread ID : 1 Message : This is message
main() : creating thread, 3
Thread ID : 2 Message : This is message
main() : creating thread, 4
Thread ID : 3 Message : This is message
Thread ID : 4 Message : This is message
自 C programming 诞生以来,其世界已经发生了很多变化,了解正在引入的新语法变得越来越重要。本文汇总了 C 语言中最流行的语法,旨在为刚开始编程旅程的人制定所有基础知识。对于更有经验的人来说,本文将概述 C++ 世界中正在发生的事情。
There has been a lot of change in the world of C programming since its inception, and it is becoming ever more important to be aware of the new syntax that is being introduced. This article provides a summary of the most popular syntaxes in C and has been designed to lay out all the basics for those who are early on in their programming journey. For those who are more experienced, this article will provide an overview of what is happening in the world of C++.