Assignment and Operations#
Base | Expression Format | Example |
---|---|---|
Binary | 0b+binary+suffix | |
Octal | 0+octal number+suffix | |
Decimal | decimal number+suffix | |
Hexadecimal | 0x+hexadecimal number+suffix | |
Suffix:
L/l
: Representslong
typeLL/ll
: Representslong long
typeU/u
: Representsunsigned
type
Type Conversion#
Order:
long double
double
float
unsigned long long
long long
unsigned long
long
unsigned int
int
Characters#
Character Data Types
Type | Memory Usage | Description | Example |
---|---|---|---|
char | 1 | Ascii character | |
wchar_t | 2/4 | Wide character | wchar_t wcharA{L'A'}; |
char16_t | 2 | utf_16 character | char16_t wchar16{u'A'}; |
char32_t | 4 | utf_32 character | char32_t wchar32{U'A'}; |
Type Inference#
// The type of variable a is float
auto a{1.0f}
// You can use typeid(a).name() to check
Formatted Output#
Method | Description |
---|---|
std::fixed | Output floating-point numbers in fixed-point notation |
std::scientific | Output decimal numbers in scientific notation |
std::defaultfloat | Restore default decimal output |
std::setprecision(int) | Set decimal precision |
std::dec | Output numbers in decimal format |
std::hex | Output numbers in hexadecimal format |
std::oct | Output numbers in octal format |
std::showbase | Show prefixes for hexadecimal and octal |
std::shownobase | Do not show prefixes for hexadecimal and octal |
std::setw(int) | Set output to a specified width |
std::setfill(char) | Fill remaining content with specified character when width exceeds character width |
std::left | Set left alignment for characters |
std::right | Set right alignment for characters |
The red methods require including the header file iomanip
.
Escape#
Operator Precedence#
Operator | Associativity |
---|---|
() [] -> . Postfix++ Postfix-- typeid const_cast dynamic_cast static_cast reinterpret_cast | Left to right |
! ~ Unary+ Unary-- Prefix++ Prefix-- & * (type) sizeof new new[] delete delete[] | Left to right |
.* 0>* | Right to left |
* / % | Left to right |
+ - | Left to right |
<< >> | Left to right |
< <= > >= | Left to right |
== != | Left to right |
& | Left to right |
^ | Left to right |
&& | Left to right |
? : op= | Right to left |
throw | Right to left |
. | Left to right |
Character Encoding#
Enumeration#
Code Example:
// Basic types can only be integral types int short
enum class TypeName: BasicType
{
Type1
}
// The default basic type is int
// If not assigned, it starts from 0 by default
enum class EquipLv {
normal,
high,
rare,
epic,
legend,
myth
};
enum class EquipLv {
normal=100,
high,
rare,
epic,
legend,
myth=1000
};
// Usage
EquipLv weaponCLV{ EquipLv::normal };
EquipLv weaponDLV{ EquipLv::legend };
Summary of Enumeration Types:
- Enumeration types can improve code readability and safety.
- The default enumeration type is int.
- Members of enumeration types can only be integral types.
- Conversion between enumeration types and other types requires explicit conversion.
- By default, the initial value of the next item in an enumeration type is the initial value of the previous item + 1.
Custom Type Names#
Ways to rename a type name: (TypeName is replaced by A)
#define TypeName A
typedef TypeName A
using A = TypeName
Namespace#
using namespace
Variable Lifetime#
- The lifetime of a variable in a code block starts from its declaration until the end of that code block.
- Variables declared before the start of the code are called global variables, and their lifetime is from the start of the program until the program ends.
- In case of variable name conflicts, the proximity principle is applied.
- To access globally scoped variables with name conflicts, you can use the qualifier
::
.
Custom Data Types#
- The essence of a structure is to define a contiguous block of memory in our own way.
- Declaring a structure variable essentially requests a block of memory from the computer, and this memory's size is at least the sum of the memory required by the defined structure members (memory alignment).
- Using a structure means reading and writing data from this block of memory according to our defined way.
Bitwise Operations#
Output Binary Content#
- Include the
bitset
header file. std::bitset<number of bits to display>(variable to display)
#include<iostream>
#include<bitset>
int main() {
int a{(int) 0b11111101111111101111111 };
std::cout << std::bitset<32>(a);
return 0;
}
00000000011111101111111101111111
D:\project\cpp\demo1\Debug\demo1.exe (process 75568) exited with code 0.
Press any key to close this window . . .
Left Shift#
<<
Right Shift#
When right-shifting signed numbers, the highest bit is filled with the sign bit.
Bitwise NOT#
~
Bitwise AND#
&
Bitwise OR#
|
Bitwise XOR#
^
Relational Operators#
Relational Operator | Description |
---|---|
> | Greater than |
< | Less than |
== | Equal to |
>= | Greater than or equal to |
<= | Less than or equal to |
!= | Not equal to |
Logical Operators#
Operator | Name | Description |
---|---|---|
&& | Logical AND | 1. Note the difference from the bitwise operator & 2. The expression is true when both operands are true |
! | Logical NOT | 1. Note the difference from the bitwise operator ~ 2. The expression is true when the operand is false |
Note:
- The precedence of unary operators is higher than that of binary operators.
- The precedence of bitwise operations is higher than that of logical operations.
- ~! > & > |
The essence of values in logical operations is to convert values into boolean values before performing logical operations.
String Handling#
String handling functions (cctype header file)
Function | Description |
---|---|
int isupper(char) | Check if the character is uppercase |
int islower(char) | Check if the character is lowercase |
int isalpha(char) | Check if the character is a letter |
int isdigit(char) | Check if the character is a digit |
int isalnum(char) | Check if the character is a letter or digit |
int isspace(char) | Check if the character is whitespace |
int isblank(char) | Check if the character is a space |
int ispunct(char) | Check if the character is punctuation |
int isprint(char) | Check if the character is printable |
int iscntrl(char) | Check if the character is a control character |
int isgraph(char) | Check if the character is a graphical character |
int tolower(char) | Convert character to lowercase |
int toupper(char) | Convert character to uppercase |
Variable in Statement Blocks#
C++17 New Syntax
if(variable lifetime; condition)
{
}
else
{
}
Formatted Stream Output and Escape#
printf
Parameter | Description |
---|---|
d | Decimal number |
o | Octal number |
u | Unsigned decimal number |
x/X | Hexadecimal integer |
f | float decimal |
lf | double decimal |
s | String |
0 | Pad with 0 |
+ | Show positive numbers |
Invisible Input#
The console will not display the input content.
The header file needs to include <conio.h>
int _getch();
#include<iostream>
#include<conio.h>
int main() {
int a = _getch();
printf("The entered character is: %d", a);
return 0;
}
goto#
#include<iostream>
int main() {
char a;
rep:
printf("Please enter an uppercase letter: ");
std::cin >> a;
if (a > 64 && a < 91 )
{
a += 32;
}
else
{
goto rep;
}
return 0;
}
Essence of Arrays#
- The essence of a one-dimensional array is to request a contiguous block of memory from the operating system according to the data type specified.
- The essence of a multi-dimensional array is also to request a contiguous block of memory from the operating system, generally sorted in a low-dimensional linear order (which may vary due to differences in operating systems and compilers), and indexing is just for convenient access to the corresponding memory area.
One-Dimensional Array#
Definition:
DataType ArrayName[ConstantExpression];
Initialization:
int a[10] = {0,1,2,3,4,5,6,7,8,9};
Two-Dimensional Array#
Definition:
DataType ArrayName[ConstantExpression1][ConstantExpression2];
Initialization:
// All defined within braces
int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
// Can omit the first dimension length
int a[][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
// Assign values to some elements
int a[3][4] = {{1},{5},{9}};
Looping Based on Arrays#
#include<iostream>
int main() {
int a[4] = { 3, 4, 2, 7 };
// First method
for (int i = 0; i < sizeof(a) / sizeof(int); i++)
{
std::cout << a[i] << std::endl;
}
// Second method
// The data type can be written as auto
for(int value :a)
{
std::cout << value << std::endl;
}
return 0;
}
std::array#
Native array + additional features
Syntax:
std::array<Type, NumberOfElements> VariableName
For example: std::array<int, 5> studentId;
Common Usage:
// Return the number of elements in studentId
studentId.size();
// Set all elements in studentId to 250
studentId.fill(250);
// Return the content of studentId[1], out of bounds will throw an error
studentId.at(1);
std::vector#
Syntax:
std::vector<DataType> VariableName
For example:
std::vector<int> studentId
Common Methods:
// Initialize a vector with elements 1,2,3
std::vector<int> studentId{1,2,3};
// Set this vector to have 5 elements
std::vector<int> studentId(5);
// Set this vector to have 5 elements, initialized to 100
std::vector<int> studentId(5, 100);
Common Methods:
Methods in std::array
can generally be used in std::vector
.
// Add value to the vector
studentId.push_back(value);
// Reinitialize studentId to have 10 elements, each element is 100
studentId.assign(10, 100);
// Clear studentId
studentId.clear();
// Check if studentId is empty
studentId.empty();
Input#
C Language#
char str[0xff];
scanf("%s", str);
wchar_t wstr[0xff];
wscanf(L"%s", wstr);
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
int main()
{
const char* username[10];
printf("Please enter your name: ");
scanf("%s", &username);
printf("\nYour name is: %s\n", username);
// Wide character
setlocale(LC_ALL, "chs");
wchar_t* w_username = new wchar_t[5];
printf("【Wide Character】Please enter your name: ");
wscanf(L"%s", &username);
wprintf(L"\n【Wide Character】Your name is: %s\n", username);
return 0;
}
Character Length#
strlen()
To find the length of wide characters:
wslen()