banner
Psycho

Psycho

#psycho

C++ Basic Knowledge

Assignment and Operations#

BaseExpression FormatExample
Binary0b+binary+suffix
Octal0+octal number+suffix
Decimaldecimal number+suffix
Hexadecimal0x+hexadecimal number+suffix

Suffix:

  • L/l: Represents long type
  • LL/ll: Represents long long type
  • U/u: Represents unsigned type

Type Conversion#

Order:

  1. long double
  2. double
  3. float
  4. unsigned long long
  5. long long
  6. unsigned long
  7. long
  8. unsigned int
  9. int

Characters#

Character Data Types

TypeMemory UsageDescriptionExample
char1Ascii character
wchar_t2/4Wide characterwchar_t wcharA{L'A'};
char16_t2utf_16 characterchar16_t wchar16{u'A'};
char32_t4utf_32 characterchar32_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#

MethodDescription
std::fixedOutputs floating-point numbers in fixed-point notation
std::scientificOutputs numbers in scientific notation
std::defaultfloatRestores default floating-point output
std::setprecision(int)Sets decimal precision
std::decOutputs numbers in decimal format
std::hexOutputs numbers in hexadecimal format
std::octOutputs numbers in octal format
std::showbaseDisplays prefixes for hexadecimal and octal
std::shownobaseDoes not display prefixes for hexadecimal and octal
std::setw(int)Sets the output to a specified width
std::setfill(char)Fills remaining content with the specified character when the display width exceeds character width
std::leftSets left alignment for characters
std::rightSets right alignment for characters

The red methods require including the header file iomanip.

Escape#

Operator Precedence#

OperatorAssociativity
() [] -> . Postfix++ Postfix-- typeid const_cast dynamic_cast static_cast reinterpret_castLeft 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
throwRight 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 with A)

  1. #define TypeName A
  2. typedef TypeName A
  3. 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.
  • A variable declared before the start of the code is called a global variable, and its 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 a globally scoped variable with a name conflict, 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#

  1. Include the bitset header file.
  2. 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 OperatorDescription
>Greater than
<Less than
==Equal to
>=Greater than or equal to
<=Less than or equal to
!=Not equal to

Logical Operators#

OperatorNameDescription
&&Logical AND1. Note the difference from the bitwise operator &
2. The expression is true when both operands are true
!Logical NOT1. 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 converting values to boolean values and then performing logical operations.

String Processing#

String processing functions (cctype header file)

FunctionDescription
int isupper(char)Checks if the character is an uppercase letter
int islower(char)Checks if the character is a lowercase letter
int isalpha(char)Checks if the character is a letter
int isdigit(char)Checks if the character is a digit
int isalnum(char)Checks if the character is a letter or digit
int isspace(char)Checks if the character is whitespace
int isblank(char)Checks if the character is a space
int ispunct(char)Checks if the character is a punctuation mark
int isprint(char)Checks if the character is printable
int iscntrl(char)Checks if the character is a control character
int isgraph(char)Checks if the character is a graphical character
int tolower(char)Converts the character to lowercase
int toupper(char)Converts the character to uppercase

Variable in Statement Blocks#

C++17 New Syntax

if(variable lifetime; condition)
{
    
} 
else 
{
       
}

Formatted Stream Output and Escape#

printf

ParameterDescription
dDecimal number
oOctal number
uUnsigned decimal number
x/XHexadecimal integer
ffloat decimal
lfdouble decimal
sString
0Pads with 0
+Displays the number

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 the index is just for convenient access to the corresponding memory area.

One-Dimensional Arrays#

Definition format:

DataType ArrayName[ConstantExpression];

Initialization format:

int a[10] = {0,1,2,3,4,5,6,7,8,9};

Two-Dimensional Arrays#

Definition format:

DataType ArrayName[ConstantExpression1][ConstantExpression2];

Initialization format:

// 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, Number of Elements> VariableName

For example: std::array<int, 5> studentId;

Common usage:

// Returns the number of elements in studentId
studentId.size();
// Sets all elements in studentId to 250
studentId.fill(250);
// Returns the content of studentId[1], out of bounds will cause an error
studentId.at(1);

std::vector#

Syntax:

std::vector<DataType> VariableName

For example:

std::vector<int> studentId

Common methods:

// Initializes a vector with elements 1,2,3
std::vector<int> studentId{1,2,3};

// Sets this vector to have 5 elements
std::vector<int> studentId(5);

// Sets this vector to have 5 elements, initialized to 100
std::vector<int> studentId(5, 100);

Common methods:

Methods from std::array can generally be used with std::vector.

// Adds a value to the vector
studentId.push_back(value);

// Reinitializes studentId to have 10 elements, each element being 100
studentId.assign(10, 100);

// Clears studentId
studentId.clear();

// Checks 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 get the length of wide characters:

wslen()

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.