Lesson 02-C++ Basic Types

Constants and Variables

Any commonly used programming language has a set of common syntax features, the most basic features include:

  • Built-in types such as integer and character
  • Variables, used to name objects
  • Expressions and statements, used to operate specific values of the above data types
  • Control structures such as if or while, to selectively execute some statements or repeatedly execute some statements
  • Functions, used to define callable computing units

Most programming languages further supplement their basic features in two ways:

  • Custom data types to extend the language
  • Encapsulate some useful functions into library functions

Constants

Constants refer to quantities whose values do not change during the execution of the program. There are two ways to define constants in C++:

Using the const keyword:

  • Constants defined using the const keyword can be assigned at runtime, but once assigned, they cannot be modified.
  • const constants can be of any data type.
#include <iostream>

int main() {
    const int MAX_SIZE = 100; // Define an integer constant
    const double PI = 3.14159; // Define a floating-point constant

    // Error: Attempt to modify constant
    // MAX_SIZE = 200; 

    std::cout << "MAX_SIZE: " << MAX_SIZE << std::endl;
    std::cout << "PI: " << PI << std::endl;

    return 0;
}

Using the constexpr keyword:

  • Constants defined by the constexpr keyword must have their values determined at compile time.
  • constexpr constants can be used to define array sizes and other values that need to be determined at compile time.
#include <iostream>

constexpr int MAX_SIZE = 100; // Compile-time constant

int main() {
    int arr[MAX_SIZE]; // Use compile-time constant to define array size

    std::cout << "Array size: " << sizeof(arr) / sizeof(arr[0]) << std::endl;

    return 0;
}

Variables

Variables provide a named, storage space that can be operated by the program. In C++, variables and objects can generally be used interchangeably.

Variable Definition (define)

  • Definition form: Type specifier (type specifier) + a list composed of one or more variable names. Such as int sum = 0, value, units_sold = 0;
  • Initialization (initialize): The object obtains a specific value when it is created.
    • Initialization is not assignment!:
    • Initialization = Create variable + Assign initial value
    • Assignment = Erase the current value of the object + Replace with a new value
    • List initialization: Use curly braces {}, such as int units_sold{0};
    • Default initialization: If no initial value is specified when defined, it will be default initialized; Built-in type variables inside the function body will not be initialized.
    • It is recommended to initialize every built-in type variable.

Variable Declaration (declaration) vs Definition (define)

  • To support separate compilation, C++ distinguishes between declaration and definition. Declaration makes the name known to the program. Definition is responsible for creating the entity associated with the name.
  • extern: Just indicates that the variable is defined elsewhere.
  • Declare only without defining: Add the keyword extern before the variable name, such as extern int i;. But if it includes an initial value, it becomes a definition: extern double pi = 3.14;
  • Variables can only be defined once, but can be declared multiple times. The definition only appears in one file, and other files need to declare it when using the variable.
  • Name’s Scope (namescope) {}
    • Define it only when the variable is used for the first time.
    • Nested scopes
      • When global and local variables exist at the same time, you can explicitly access the global variable reused using ::reused in the scope where the local variable is defined.
      • However, when using global variables, try not to use local variables with the same name.

Variable Naming Conventions

  1. Must reflect actual meaning
  2. Variable names use lowercase letters
  3. Custom class names start with uppercase letters: Sales_item
  4. If the identifier consists of multiple words, there must be a clear distinction in the middle: student_loan or studentLoan, do not use studentloan.

Variables are identifiers used to store data. In C++, variables must be declared before use.

Declaring Variables

// Declare an integer variable
int age;

// Declare and initialize a floating-point variable
double pi = 3.14159;

// Declare and initialize a character variable
char grade = 'A';

Initializing Variables

// Initialize multiple variables
int x = 10, y = 20;

// Initialize a boolean variable
bool isTrue = true;

Using Constants and Variables

Next, let’s look at a comprehensive example showing how to use constants and variables for some basic operations.

#include <iostream>

int main() {
    // Declare and initialize variables
    int age = 25;
    double salary = 50000.0;
    bool isStudent = false;

    // Use constants
    constexpr int MAX_AGE = 150;
    const double TAX_RATE = 0.2;

    // Calculate net salary after tax
    double netSalary = salary * (1 - TAX_RATE);

    std::cout << "Age: " << age << std::endl;
    std::cout << "Salary: $" << salary << std::endl;
    std::cout << "Net Salary after tax: $" << netSalary << std::endl;
    std::cout << "Is student: " << (isStudent ? "Yes" : "No") << std::endl;

    return 0;
}

Data Types

Integer Types:

  • char: 8-bit signed integer.
  • short: Usually 16-bit signed integer.
  • int: Usually 32-bit signed integer.
  • long: At least 32-bit signed integer.
  • long long: At least 64-bit signed integer.
  • unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long: Corresponding unsigned integer types.

Floating-Point Types:

  • float: Single-precision floating-point number.
  • double: Double-precision floating-point number.
  • long double: Extended-precision floating-point number.

Boolean Type:

  • bool: Boolean value, can be true or false.

Character Types:

  • char: Character type.
  • wchar_t: Wide character type, usually used for Unicode characters.

Void Type:

  • void: Void type, used to indicate no type.

Basic Arithmetic Types:

TypeMeaningMinimum Size
boolBoolean type8bits
charCharacter8bits
wchar_tWide character16bits
char16_tUnicode character16bits
char32_tUnicode character32bits
shortShort integer16bits
intInteger16bits (32bits on 32-bit machines)
longLong integer32bits
long longLong integer64bits (Newly defined in C++11)
floatSingle-precision floating-point6 significant digits
doubleDouble-precision floating-point10 significant digits
long doubleExtended-precision floating-point10 significant digits

How to Choose Types

    1. When it is clearly known that the value cannot be negative, choose unsigned type;
    1. Use int for integer operations. Generally, the size of long is the same as int, while short often seems too small. Unless it exceeds the range of int, choose long long.
    1. Do not use char or bool in arithmetic expressions.
    1. Use double for floating-point operations.

Type Conversion

  • Non-boolean assigned to boolean, if the initial value is 0, the result is false, otherwise true.
  • Boolean assigned to non-boolean, if the initial value is false, the result is 0, if true, the result is 1.

Literal Constants

  • A value like 42 is called a literal constant (literal).
    • Integer and floating-point literals.
    • Character and string literals.
      • Connect using spaces, inherited from C.
      • Character literal: Single quotes, 'a'
      • String literal: Double quotes, "Hello World"
      • Split string across multiple lines. std:cout<<"wow, a really, really long string" "literal that spans two lines" <<std::endl;
    • Escape sequences. \n, \t, etc.
    • Boolean literals. true, false.
    • Pointer literal. nullptr

String type is actually an array of constant characters, ending with '\0', so the actual length of string type is 1 more than the content.

Operators

Arithmetic Operators

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Division
  • %: Modulo (remainder)
#include <iostream>

int main() {
    int a = 10, b = 3;
    std::cout << "a + b = " << a + b << std::endl;
    std::cout << "a - b = " << a - b << std::endl;
    std::cout << "a * b = " << a * b << std::endl;
    std::cout << "a / b = " << a / b << std::endl;
    std::cout << "a % b = " << a % b << std::endl;

    return 0;
}

Relational Operators

  • <: Less than
  • >: Greater than
  • <=: Less than or equal to
  • >=: Greater than or equal to
  • ==: Equal to
  • !=: Not equal to
#include <iostream>

int main() {
    int a = 10, b = 3;
    std::cout << "a < b = " << (a < b) << std::endl;
    std::cout << "a > b = " << (a > b) << std::endl;
    std::cout << "a <= b = " << (a <= b) << std::endl;
    std::cout << "a >= b = " << (a >= b) << std::endl;
    std::cout << "a == b = " << (a == b) << std::endl;
    std::cout << "a != b = " << (a != b) << std::endl;

    return 0;
}

Logical Operators

  • !: Logical NOT
  • &&: Logical AND
  • ||: Logical OR
#include <iostream>

int main() {
    bool a = true, b = false;
    std::cout << "!a = " << !a << std::endl;
    std::cout << "a && b = " << (a && b) << std::endl;
    std::cout << "a || b = " << (a || b) << std::endl;

    return 0;
}

Bitwise Operators

  • ~: Bitwise NOT
  • &: Bitwise AND
  • |: Bitwise OR
  • ^: Bitwise XOR
  • <<: Left shift
  • >>: Right shift
#include <iostream>

int main() {
    int a = 10, b = 3;
    std::cout << "~a = " << ~a << std::endl;
    std::cout << "a & b = " << (a & b) << std::endl;
    std::cout << "a | b = " << (a | b) << std::endl;
    std::cout << "a ^ b = " << (a ^ b) << std::endl;
    std::cout << "a << 1 = " << (a << 1) << std::endl;
    std::cout << "a >> 1 = " << (a >> 1) << std::endl;

    return 0;
}

Assignment Operators

  • =: Simple assignment
  • +=: Addition assignment
  • -=: Subtraction assignment
  • *=: Multiplication assignment
  • /=: Division assignment
  • %=: Modulo assignment
  • &=: Bitwise AND assignment
  • |=: Bitwise OR assignment
  • ^=: Bitwise XOR assignment
  • <<=: Left shift assignment
  • >>=: Right shift assignment
#include <iostream>

int main() {
    int a = 10;
    a += 5;
    std::cout << "a += 5: " << a << std::endl;

    a -= 3;
    std::cout << "a -= 3: " << a << std::endl;

    a *= 2;
    std::cout << "a *= 2: " << a << std::endl;

    a /= 4;
    std::cout << "a /= 4: " << a << std::endl;

    a %= 3;
    std::cout << "a %= 3: " << a << std::endl;

    a &= 1;
    std::cout << "a &= 1: " << a << std::endl;

    a |= 2;
    std::cout << "a |= 2: " << a << std::endl;

    a ^= 3;
    std::cout << "a ^= 3: " << a << std::endl;

    a <<= 1;
    std::cout << "a <<= 1: " << a << std::endl;

    a >>= 1;
    std::cout << "a >>= 1: " << a << std::endl;

    return 0;
}

Strings

using Declaration

  • Use a certain namespace: For example, using std::cin means using the name cin in the namespace std.
  • Header files should not contain using declarations. This way, the source code using the header file will also use this declaration, which may bring risks.

string

  • The standard library type string represents a variable-length sequence of characters.
  • #include <string>, then using std::string;
  • string object: Note that it is different from string literals.

Defining and Initializing string Objects

Ways to initialize string objects:

WayExplanation
string s1Default initialization, s1 is an empty string
string s2(s1)s2 is a copy of s1
string s2 = s1Equivalent to s2(s1), s2 is a copy of s1
string s3("value")s3 is a copy of the literal “value”, except for the last null character of the literal
string s3 = "value"Equivalent to s3("value"), s3 is a copy of the literal “value”
string s4(n, 'c')Initialize s4 as a string consisting of consecutive n characters c
  • Copy initialization (copy initialization): Use the equal sign = to copy an existing object to the object being created.
  • Direct initialization (direct initialization): Assign values to the object through parentheses.

Operations on string Objects

Operations on string:

OperationExplanation
os << sWrite s to the output stream os, return os
is >> sRead string from is and assign to s, strings are separated by spaces, return is
getline(is, s)Read a line from is and assign to s, return is
s.empty()Return true if s is empty, otherwise return false
s.size()Return the number of characters in s
s[n]Return a reference to the nth character in s, position n starts from 0
s1+s2Return the result of connecting s1 and s2
s1=s2Replace the original characters in s1 with a copy of s2
s1==s2If the characters contained in s1 and s2 are exactly the same, they are equal; the equality judgment of string objects is case-sensitive
s1!=s2Same as above
<, <=, >, >=Compare using the dictionary order of characters, and case-sensitive (compare the first different position)
  • string io:
    • Perform read operation >>: Ignore leading spaces (including spaces, newlines, and tabs), until the next space is encountered.
    • getline: Read a whole line, including spaces.
  • s.size() returns string::size_type type, remember it is an unsigned type value, do not mix with int
  • When using s1+s2, ensure that at least one side is string type. string s1 = "hello" + "world" // Error, both sides are string literals
  • String literals and string are different types.

Processing Characters in string Objects

  • ctype.h vs. cctype: C++ modifies the C standard library, the name removes .h, adds c in front. For example, the C++ version is cctype, the C version is ctype.h
    • Try to use the C++ version of the header file, i.e., cctype

The cctype header file defines a set of standard functions:

FunctionExplanation
isalnum(c)True when c is a letter or digit
isalpha(c)True when c is a letter
iscntrl(c)True when c is a control character
isdigit(c)True when c is a digit
isgraph(c)True when c is not a space but printable
islower(c)True when c is a lowercase letter
isprint(c)True when c is a printable character
ispunct(c)True when c is a punctuation mark
isspace(c)True when c is a space (space, horizontal tab, vertical tab, carriage return, newline, form feed)
isupper(c)True when c is an uppercase letter
isxdigit(c)True when c is a hexadecimal digit
tolower(c)If c is uppercase, output the corresponding lowercase; otherwise output c as is
toupper(c)If c is lowercase, output the corresponding uppercase; otherwise output c as is
  • Traverse string: Use range for statement: for (auto c: str), or for (auto &c: str) use reference to directly change characters in the string. (C++11)
  • s[x], [] input parameter is string::size_type type, giving int integer will also be automatically converted to this type

C-Style Strings

C-style strings are arrays of characters, ending with a null character (\0) as the terminator.

Defining C-Style Strings

char str[] = "Hello, world!"; // Automatically adds \0 at the end
char str2[20] = "Hello";       // Manually specify size

Operations on C-Style Strings

C-style strings require manual handling of the null terminator. Common functions include strcpy, strcat, strlen, etc.

#include <iostream>
#include <cstring>

int main() {
    char src[50] = "Hello";
    char dest[50];

    // Copy string
    strcpy(dest, src);
    std::cout << "Copied string: " << dest << std::endl;

    // Concatenate strings
    strcat(src, ", world!");
    std::cout << "Concatenated string: " << src << std::endl;

    // Get string length
    std::cout << "Length of src: " << strlen(src) << std::endl;

    return 0;
}

Comparing C-Style Strings

Use strcmp to compare two C-style strings.

#include <iostream>
#include <cstring>

int main() {
    char str1[] = "apple";
    char str2[] = "banana";

    int result = strcmp(str1, str2);
    if (result < 0) {
        std::cout << str1 << " comes before " << str2 << std::endl;
    } else if (result > 0) {
        std::cout << str1 << " comes after " << str2 << std::endl;
    } else {
        std::cout << str1 << " is equal to " << str2 << std::endl;
    }

    return 0;
}

Converting Between std::string and C-Style Strings

Use c_str() to get a const char* from std::string.

#include <iostream>
#include <string>

int main() {
    std::string stdStr = "Hello, world!";
    const char* cStr = stdStr.c_str();

    std::cout << "C-style string: " << cStr << std::endl;

    return 0;
}

Basic Operations on std::string

Initialization

#include <iostream>
#include <string>

int main() {
    std::string str1;             // Empty string
    std::string str2 = "Hello";   // Initialize with string literal
    std::string str3(5, 'a');     // "aaaaa"

    std::cout << "str1: " << str1 << std::endl;
    std::cout << "str2: " << str2 << std::endl;
    std::cout << "str3: " << str3 << std::endl;

    return 0;
}

Concatenation

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello";
    std::string str2 = "World";

    std::string str3 = str1 + ", " + str2 + "!";
    std::cout << "Concatenated string: " << str3 << std::endl;

    return 0;
}

Accessing Characters

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello";

    // Access first character
    char firstChar = str[0];
    std::cout << "First character: " << firstChar << std::endl;

    // Modify last character
    str[str.length() - 1] = '!';
    std::cout << "Modified string: " << str << std::endl;

    return 0;
}

Substrings

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";

    // Extract substring starting from index 7 with length 5
    std::string sub = str.substr(7, 5);
    std::cout << "Substring: " << sub << std::endl;

    return 0;
}

Finding Substrings

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello, world!";
    std::string str2 = "lo";

    size_t pos = str1.find(str2);
    if (pos != std::string::npos) {
        std::cout << "Found substring at position: " << pos << std::endl;
    } else {
        std::cout << "Substring not found." << std::endl;
    }

    return 0;
}

Replacing Substrings

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Hello, world!";
    std::string str2 = "lo";

    size_t pos = str1.find(str2);
    if (pos != std::string::npos) {
        std::cout << "Found substring at position: " << pos << std::endl;

    // Replace substring
    str1.replace(pos, 2, "LO");
    std::cout << "Replaced string: " << str1 << std::endl;

    return 0;
}

Other Common Operations

In addition to the above basic operations, the std::string class also provides many other useful functions, such as case conversion, string splitting, etc.

#include <iostream>
#include <string>
#include <algorithm> // Contains transform function

int main() {
    std::string str = "Hello World";

    // Convert to uppercase
    std::transform(str.begin(), str.end(), str.begin(), ::toupper);
    std::cout << "Uppercase: " << str << std::endl;

    // Convert to lowercase
    std::transform(str.begin(), str.end(), str.begin(), ::tolower);
    std::cout << "Lowercase: " << str << std::endl;

    // Split string
    std::string delimiter = " ";
    size_t start = 0, end = str.find(delimiter);
    while (end != std::string::npos) {
        std::cout << "Token: " << str.substr(start, end - start) << std::endl;
        start = end + delimiter.length();
        end = str.find(delimiter, start);
    }
    std::cout << "Last token: " << str.substr(start, end) << std::endl;

    return 0;
}

Pointer Types

Pointer Basics

Defining Pointers Pointer variables are variables used to store the memory addresses of other variables. The basic syntax for defining pointers is as follows:

type *pointer_name;

Here type is the data type of the variable pointed to by the pointer, pointer_name is the name of the pointer variable.

Initializing Pointers Pointers can be initialized to nullptr or point to the address of a variable.

int x = 10;
int *p = nullptr; // Initialize to null pointer
p = &x;           // Point to the address of variable x

Accessing Data Pointed to by Pointers Use the * operator to access the value at the memory location pointed to by the pointer.

int value = *p;   // Get the value of x

Getting Variable Address Use the & operator to get the address of a variable.

int *q = &x;      // q points to the address of x

Pointer Operations

Pointer Arithmetic Pointers can be operated using arithmetic operators, such as adding or subtracting integers.

int arr[5] = {0, 1, 2, 3, 4};
int *ptr = &arr[0]; // Point to the first element of the array

// Move pointer to the next element
ptr++; // Equivalent to ptr = ptr + 1;
int nextValue = *ptr; // Value of the next element

Pointers and Arrays The array name is actually a constant pointer to the first element of the array.

int arr[5] = {0, 1, 2, 3, 4};
int *p = arr;          // p and arr point to the same location
int firstElement = *p; // Get the first element

Dynamic Memory Allocation Use the new and delete operators to dynamically allocate and release memory.

int *dynamicPtr = new int; // Allocate memory for an int
*dynamicPtr = 42;          // Assign value to this int
delete dynamicPtr;         // Release memory

Pointer Example Code

Printing Array Using Pointers

#include <iostream>

void printArray(int *arr, int size) {
    for (int i = 0; i < size; ++i) {
        std::cout << *(arr + i) << " ";
    }
    std::cout << std::endl;
}

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    printArray(arr, 5);

    return 0;
}

Dynamically Allocating Array

#include <iostream>

int main() {
    int *dynamicArr;
    int size = 5;

    dynamicArr = new int[size];

    for (int i = 0; i < size; ++i) {
        dynamicArr[i] = i * i;
    }

    for (int i = 0; i < size; ++i) {
        std::cout << dynamicArr[i] << " ";
    }
    std::cout << std::endl;

    delete[] dynamicArr; // Release array memory

    return 0;
}

Pointers and Functions

#include <iostream>

void incrementThroughPointer(int *ptr) {
    (*ptr)++;
}

int main() {
    int x = 10;
    int *ptr = &x;

    std::cout << "Before: " << x << std::endl;
    incrementThroughPointer(ptr);
    std::cout << "After: " << x << std::endl;

    return 0;
}

Reference Types

Definition of References

The basic syntax for defining references is as follows:

type& ref_name = var_name;

Here type is the data type of the variable referenced, ref_name is the name of the reference, and var_name is the referenced variable.

Features

  • References must be initialized at definition.
  • Once a reference is initialized to a variable, the referenced object cannot be changed.
  • References are not pointers, no nullptr value, and no dereferencing needed.

Usage Scenarios

  • Function Parameters: Can avoid copy costs, especially when passing large objects.
  • Function Return Values: Can return large objects without copying.
  • Class Members: Can create references to other objects instead of copying.

Example Code

Here are some examples of references.

Basic Reference

#include <iostream>

int main() {
    int x = 10;
    int& r = x; // r is a reference to x

    std::cout << "x: " << x << ", r: " << r << std::endl;
    r = 20;     // Modify the value of x
    std::cout << "x: " << x << ", r: " << r << std::endl;

    return 0;
}

Reference as Function Parameter

#include <iostream>

void swap(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 10, y = 20;
    std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;
    swap(x, y);
    std::cout << "After swap: x = " << x << ", y = " << y << std::endl;

    return 0;
}

Reference as Function Return Value

#include <iostream>

class Counter {
public:
    int& getCounter() {
        return counter; // Return reference
    }

private:
    int counter = 0;
};

int main() {
    Counter c;
    int& ref = c.getCounter();
    ref = 5;
    std::cout << "Counter: " << ref << std::endl;

    return 0;
}

Notes

  • References must be initialized at definition.
  • References cannot be rebound to another object.
  • References always point to the object they were initialized with.
  • References are not pointers, so arithmetic operations cannot be performed on them.

Const References To avoid modifying the referenced object, you can use const references:

const type& ref_name = var_name;

This prevents modifying the original object through the reference, often used to pass large objects to functions to avoid unnecessary copies.

Const Reference

#include <iostream>
#include <string>

void printString(const std::string& s) {
    std::cout << "String: " << s << std::endl;
}

int main() {
    std::string str = "Hello, world!";
    printString(str);

    return 0;
}

Boolean Types

Definition of Boolean Types

bool variable_name;

Assignment of Boolean Types

bool isTrue = true;
bool isFalse = false;

Default Value of Boolean Types If a boolean variable is not initialized, its default value is false.

Numeric Representation of Boolean Types Internally, true is usually represented as the integer value 1, and false as the integer value 0. This means boolean values can be compared with other integer values or participate in arithmetic operations.

Conversion Between Boolean Types and Integers

  • When an integer value is converted to a boolean, 0 is treated as false, and any non-zero value as true.
  • When a boolean value is converted to an integer, false is converted to 0, and true to 1.

Example Code Here is a simple example demonstrating how to use boolean types.

#include <iostream>

int main() {
    bool flag = true;
    bool result;

    // Boolean expression
    result = (flag && true); // Result is true
    std::cout << "Result of (flag && true): " << result << std::endl;

    // Conversion between boolean and integer
    int intValue = 10;
    bool boolFromInt = intValue; // If intValue is non-zero, boolFromInt is true
    std::cout << "boolFromInt from intValue: " << boolFromInt << std::endl;

    // Conversion between integer and boolean
    int intFromBool = flag; // If flag is true, intFromBool is 1
    std::cout << "intFromBool from flag: " << intFromBool << std::endl;

    return 0;
}

Application of Boolean Types in Conditional Statements

Boolean types are often used in conditional judgments and logical operations. For example, if statements can accept boolean expressions as conditions.

#include <iostream>

int main() {
    bool isReady = false;

    if (isReady) {
        std::cout << "Ready to proceed." << std::endl;
    } else {
        std::cout << "Not ready yet." << std::endl;
    }

    return 0;
}

Application of Boolean Types in Loops

Boolean types can also be used in loop conditions, such as while loops.

#include <iostream>

int main() {
    bool continueLoop = true;
    int count = 0;

    while (continueLoop) {
        std::cout << "Count: " << count << std::endl;
        if (++count == 5) {
            continueLoop = false; // Stop the loop
        }
    }

    return 0;
}

Structs

Struct Definition

The basic definition form of a struct is as follows:

struct struct_name {
    member_type member_name;
    // More members
};

Each struct can contain different types of data members, including basic types (such as int, float), and can also contain instances of other structs or classes.

Struct Instantiation After defining a struct, you can create an instance of the struct in the following way:

struct_name instance_name;

Accessing Struct Members

Struct members can be accessed through the member access operator . :

instance_name.member_name;

Example Code Here is a simple struct example showing how to define and use a struct.

Defining and Using Struct

#include <iostream>

struct Point {
    double x;
    double y;
};

int main() {
    Point p1; // Create an instance of Point struct
    p1.x = 10.5;
    p1.y = 20.5;

    std::cout << "Point coordinates: (" << p1.x << ", " << p1.y << ")" << std::endl;

    return 0;
}

Differences Between Structs and Classes

In C++, structs and classes are very similar, but there are a few key differences:

  • By default, struct members are public, while class members are private.
  • Structs can contain function members, just like classes.
  • Structs can inherit other structs or classes, and can also be inherited.

Example Code

Here is a more complex example showing struct member functions and inheritance.

Struct Member Functions and Inheritance

#include <iostream>

struct Point {
    double x;
    double y;

    void setCoordinates(double newX, double newY) {
        x = newX;
        y = newY;
    }

    void printCoordinates() const {
        std::cout << "Point coordinates: (" << x << ", " << y << ")" << std::endl;
    }
};

struct ColoredPoint : public Point {
    std::string color;

    ColoredPoint(std::string col) : color(col) {}

    void setColor(std::string newColor) {
        color = newColor;
    }

    void printColoredCoordinates() const {
        printCoordinates();
        std::cout << "Color: " << color << std::endl;
    }
};

int main() {
    Point p1;
    p1.setCoordinates(10.5, 20.5);
    p1.printCoordinates();

    ColoredPoint cp1("red");
    cp1.setCoordinates(15.5, 25.5);
    cp1.setColor("blue");
    cp1.printColoredCoordinates();

    return 0;
}

Structs and typedef

Using typedef can simplify the use of structs. For example, you can define an alias for the struct.

#include <iostream>

typedef struct {
    double x;
    double y;
} Point;

int main() {
    Point p1;
    p1.x = 10.5;
    p1.y = 20.5;

    std::cout << "Point coordinates: (" << p1.x << ", " << p1.y << ")" << std::endl;

    return 0;
}

Enumeration Types

Definition of Enumeration Types

The definition of enumeration types uses the enum keyword, with the basic syntax as follows:

enum enum_name {
    enumerator1,
    enumerator2,
    // More enumerators
};

Each enumerator starts incrementing from 0 by default, but you can also explicitly specify their values.

Use of Enumeration Types

Members of enumeration types can be accessed directly through the enumeration name, or an alias can be defined at the same time as defining the enumeration type.

Example 1: Basic Enumeration Type

#include <iostream>

enum Season {
    Spring,
    Summer,
    Autumn,
    Winter
};

int main() {
    Season currentSeason = Summer;

    switch (currentSeason) {
    case Spring:
        std::cout << "It's Spring." << std::endl;
        break;
    case Summer:
        std::cout << "It's Summer." << std::endl;
        break;
    case Autumn:
        std::cout << "It's Autumn." << std::endl;
        break;
    case Winter:
        std::cout << "It's Winter." << std::endl;
        break;
    }

    return 0;
}

Explicitly Assigned Enumeration Type

#include <iostream>

enum Color {
    Red = 1,
    Green = 2,
    Blue = 4
};

int main() {
    Color c1 = Red;
    Color c2 = Green | Blue; // Use bitwise OR operator to combine multiple enumerators

    std::cout << "c1: " << c1 << std::endl;
    std::cout << "c2: " << c2 << std::endl;

    return 0;
}

Enumeration Type Alias

#include <iostream>

enum class Color {
    Red,
    Green,
    Blue
};

int main() {
    using MyColor = Color; // Use typedef syntax sugar

    MyColor myColor = Color::Green;

    std::cout << "MyColor: " << static_cast<int>(myColor) << std::endl;

    return 0;
}

Notes on Enumeration Types

  • Enumerators start from 0 by default, but can be controlled by explicit assignment.
  • Enumeration types can be defined using enum or enum class keywords.
  • enum class provides better type safety and scope isolation.
  • Enumerators can be compared with other integer values or participate in arithmetic operations.
  • Enumeration types can be used in switch statements.

Conversion Between Enumeration Types and Integers

Enumerators can be implicitly converted to integers, or explicitly converted using static_cast<int>().

Scope of Enumeration Types

The default scope of enumeration types depends on the compiler, but can be controlled by specifying the underlying type:

enum class Color : unsigned char {
    Red,
    Green,
    Blue
};

Array Types

Declaring Arrays:

The basic syntax for declaring an array is as follows:

dataType arrayName[arraySize];

Where dataType is the data type of the array elements, arrayName is the name of the array, and arraySize is the size of the array (i.e., the number of elements in the array). The array size must be a constant expression.

Initializing Arrays:

Arrays can be initialized at the time of declaration, for example:

int numbers[] = {1, 2, 3, 4, 5};

If an initializer list is provided, the array size can be omitted:

int numbers[] = {1, 2, 3, 4, 5}; // The compiler will automatically calculate the array size

You can also explicitly specify the size and partially initialize:

int numbers[10] = {0, 1, 2}; // Remaining elements will be initialized to 0

Accessing Array Elements:

Array elements can be accessed via indexing, with indices starting from 0:

int firstElement = numbers[0]; // Access the first element

Multidimensional Arrays:

Multidimensional arrays can be used to represent matrices or tables. For example, a two-dimensional array:

int matrix[3][4]; // A 3-row, 4-column integer matrix

Initializing a Two-Dimensional Array:

int matrix[3][4] = {
  {1, 2, 3, 4},
  {5, 6, 7, 8},
  {9, 10, 11, 12}
};

Traversing Arrays:

Loop structures can be used to traverse all elements of an array:

for (int i = 0; i < 5; ++i) {
  std::cout << numbers[i] << " ";
}

Arrays and Pointers:

In C++, the array name is actually a pointer to the first element of the array. This means you can use pointer arithmetic to access array elements:

int *ptr = numbers;
std::cout << *(ptr + 2); // Output the third element

begin and end Functions in C++11:

These two functions can be used to obtain iterators pointing to the beginning and end of the array, facilitating traversal:

#include <iterator>
...
auto it = std::begin(numbers);
auto endIt = std::end(numbers);
while (it != endIt) {
  std::cout << *it << " ";
  ++it;
}

Dynamic Arrays:

Use the new keyword to allocate arrays at runtime and delete[] to free the memory:

int *dynamicArray = new int[5];
dynamicArray[0] = 10;
delete[] dynamicArray; // Free the memory

Arrays as Function Parameters

  • Arrays can be passed as function parameters, typically implemented using pointers.
  • When an array is passed to a function, it decays into a pointer.
#include <iostream>

void printArray(int arr[], int size) {
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    printArray(numbers, size);

    return 0;
}

Copying Arrays

Copying arrays usually requires manual operation, using loops or the standard library function std::copy.

#include <algorithm> // Include std::copy
#include <iostream>

int main() {
    int source[] = {1, 2, 3, 4, 5};
    int dest[5];

    std::copy(std::begin(source), std::end(source), dest);

    for (int i = 0; i < 5; ++i) {
        std::cout << dest[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

Sorting Arrays

The standard library function std::sort can be used to sort arrays.

#include <algorithm> // Include std::sort
#include <iostream>

int main() {
    int numbers[] = {5, 2, 3, 1, 4};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    std::sort(std::begin(numbers), std::end(numbers));

    for (int i = 0; i < size; ++i) {
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

Finding Elements in Arrays

The std::find function can be used to search for a specific element in an array.

#include <algorithm> // Include std::find
#include <iostream>

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    int target = 3;
    auto it = std::find(std::begin(numbers), std::end(numbers), target);

    if (it != std::end(numbers)) {
        std::cout << "Found " << target << " at index: " << it - std::begin(numbers) << std::endl;
    } else {
        std::cout << "Not found" << std::endl;
    }

    return 0;
}

Common Array Operations

In addition to the above operations, std::reverse can be used to reverse an array, and std::unique to remove duplicate elements, etc.

#include <algorithm> // Include std::reverse
#include <iostream>

int main() {
    int numbers[] = {1, 2, 3, 4, 5};
    int size = sizeof(numbers) / sizeof(numbers[0]);

    std::reverse(std::begin(numbers), std::end(numbers));

    for (int i = 0; i < size; ++i) {
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

vector Container Type

In C++, std::vector is a very important container type in the Standard Template Library (STL), providing dynamic array functionality. The std::vector container can store elements of any type and automatically resize as needed.

  • vector is a container and also a class template;
  • #include <vector> then using std::vector;
  • Container: contains other objects.
  • Class template: not a class itself, but can be instantiated into a class. vector is a template, vector<int> is a type.
  • Specify the type by placing it in angle brackets after the class template name, e.g., vector<int> ivec.

Here are some key characteristics of std::vector:

Dynamic Size:

  • std::vector can automatically grow or shrink its size as needed, making it more flexible than traditional C-style arrays.
  • When the size of std::vector changes, it reallocates memory and copies existing elements to the new memory location.

Random Access:

  • std::vector supports random access, meaning any element can be accessed quickly via subscript.
  • This access method has a time complexity of O(1), i.e., constant time.

Initialization:

  • std::vector can be initialized at creation or elements can be added after creation.
  • The basic syntax for creating a std::vector is as follows:
std::vector<int> vec; // Create an empty vector
std::vector<int> vec(10, 0); // Create a vector with 10 elements, each initialized to 0

Inserting and Deleting Elements:

  • Use the push_back() method to add elements to the end of std::vector.
  • Use the pop_back() method to remove elements from the end of std::vector.
  • Use the insert() and erase() methods to insert or delete elements at any position.

Capacity and Size:

  • The size() method returns the current number of elements in std::vector.
  • The capacity() method returns the number of elements that the allocated memory can hold.
  • The reserve() method can pre-allocate enough memory to hold a specified number of elements, avoiding frequent reallocations.

Iterators:

  • std::vector provides iterators for traversing elements in the container.
  • Use the begin() and end() methods to obtain iterators pointing to the beginning and end of the container.

Common Methods:

  • clear() clears all elements.
  • empty() checks if the container is empty.
  • at() gets the element at a specified position, throws an exception if the index is out of bounds.
  • front() gets the first element.
  • back() gets the last element.

Here is a simple example of using std::vector:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec;

    // Add elements to the vector
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);

    // Output all elements in the vector
    for (int elem : vec) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    // Remove the last element
    vec.pop_back();

    // Output the modified vector
    for (int elem : vec) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    return 0;
}

This code creates a std::vector<int>, adds three integers to it, outputs these elements, then removes the last element and outputs the remaining elements again.

Defining and Initializing vector Objects

Methods to initialize vector objects

MethodExplanation
vector<T> v1v1 is an empty vector, its potential elements are of type T, performing default initialization
vector<T> v2(v1)v2 contains copies of all elements from v1
vector<T> v2 = v1Equivalent to v2(v1), v2 contains copies of all elements from v1
vector<T> v3(n, val)v3 contains n repeated elements, each with the value val
vector<T> v4(n)v4 contains n objects that have undergone value initialization repeatedly
vector<T> v5{a, b, c...}v5 contains a number of elements equal to the initial values, each assigned the corresponding initial value
vector<T> v5={a, b, c...}Equivalent to v5{a, b, c...}
  • List initialization: vector<string> v{"a", "an", "the"}; (C++11)

Adding Elements to vector Objects

  • v.push_back(e) adds an element to the tail.

Other vector Operations

Operations supported by vector:

OperationExplanation
v.empty()Returns true if v contains no elements; otherwise false
v.size()Returns the number of elements in v
v.push_back(t)Adds an element with value t to the end of v
v[n]Returns a reference to the element at position n in v
v1 = v2Replaces elements in v1 with copies of elements from v2
v1 = {a,b,c...}Replaces elements in v1 with copies of elements from the list
v1 == v2v1 and v2 are equal if and only if they have the same number of elements and corresponding elements have the same values
v1 != v2As above
<,<=,>, >=Compared in dictionary order
  • Do not change the size of the traversed sequence within a range for statement.
  • The subscript operator of vector objects (and string objects) can only be used on elements that are known to exist and cannot be used to add elements.

Iterator

  • All standard library containers can use iterators.
  • Similar to pointer types, iterators also provide indirect access to objects.

Using Iterators

  • vector<int>::iterator iter.
  • auto b = v.begin(); returns an iterator pointing to the first element.
  • auto e = v.end(); returns an iterator pointing to one past the last element (sentinel, off the end).
  • If the container is empty, begin() and end() return the same iterator, which is the off-the-end iterator.
  • Use the dereference operator * to access the element pointed to by the iterator.
  • Develop the habit of using iterators and != (generic programming).
  • Container: can contain other objects; but all objects must be of the same type.
  • Iterator: each standard container has its own iterator. C++ tends to use iterators rather than subscripts to traverse elements.
  • const_iterator: can only read elements in the container, cannot modify them.
  • Arrow operator: dereference + member access, it->mem is equivalent to (*it).mem
  • Remember: in any loop body that uses iterators, do not add elements to the container to which the iterator belongs.

Standard container iterator operators:

OperatorExplanation
*iterReturns a reference to the element pointed to by iterator iter
iter->memEquivalent to (*iter).mem
++iterMakes iter point to the next element in the container
--iterMakes iter point to the previous element in the container
iter1 == iter2Judges whether two iterators are equal

Iterator Arithmetic

Operations supported by vector and string iterators:

OperatorExplanation
iter + nAdding an integer to an iterator still yields an iterator, the new iterator points to a position moved forward by several elements from the original. The result iterator either points to an element in the container or to the position after the last element.
iter - nSubtracting an integer from an iterator still yields an iterator, the new iterator points to a position moved backward by several elements from the original. The result iterator either points to an element in the container or to the position after the last element.
iter1 += nIterator addition compound assignment, assigns the result of iter1 plus n to iter1
iter1 -= nIterator subtraction compound assignment, assigns the result of iter1 minus n to iter1
iter1 - iter2The result of subtracting two iterators is the distance between them, meaning moving the right-hand iterator forward by the difference yields the left-hand iterator. The two iterators involved must point to elements in the same container or to the position after the last element.
>、>=、<、<=Iterator relational operators, if one iterator points to a position before another iterator in the container, the former is less than the latter. The two iterators involved must point to elements in the same container or to the position after the last element.
  • difference_type: guaranteed to be large enough to store the distance between any two iterator objects, can be positive or negative.

Complex Number Type

  • The std::complex type is used to represent complex numbers, which have two parts: real and imaginary. Both parts are floating-point numbers.
#include <iostream>
#include <complex>

int main() {
    std::complex<double> c1(3.0, 4.0); // Real part 3.0, imaginary part 4.0
    std::complex<double> c2(1.0, 2.0); // Real part 1.0, imaginary part 2.0

    std::complex<double> sum = c1 + c2; // Complex addition

    std::cout << "Sum: " << sum.real() << " + " << sum.imag() << "i" << std::endl;

    return 0;
}

typedef Name

typedef defines an alias for a type

#include <iostream>
#include <complex>

typedef std::complex<double> ComplexDouble;

int main() {
    ComplexDouble c1(3.0, 4.0);
    ComplexDouble c2(1.0, 2.0);

    ComplexDouble sum = c1 + c2;

    std::cout << "Sum: " << sum.real() << " + " << sum.imag() << "i" << std::endl;

    return 0;
}

volatile Qualifier

The volatile keyword tells the compiler that a variable might be changed by external factors during program execution, so the compiler should not optimize this variable

#include <iostream>
#include <complex>

typedef std::complex<double> ComplexDouble;

int main() {
    volatile ComplexDouble v_complex(3.0, 4.0); // volatile qualifier

    // Assume v_complex is changed by external hardware
    // ...

    std::cout << "Value: " << v_complex.real() << " + " << v_complex.imag() << "i" << std::endl;

    return 0;
}

In this example, we define a volatile ComplexDouble variable v_complex. This means that even if the value of v_complex is not explicitly changed in the code, the compiler should ensure that each access to v_complex reads the latest value from memory, rather than using an old value in a register.

pair Type

The std::pair type is used to store two values, which can be of different types. std::pair provides two member variables: first and second, used to store the two values respectively.

#include <iostream>
#include <utility> // Include std::pair

int main() {
    // Create a pair object
    std::pair<int, std::string> person(1, "Alice");

    // Access pair elements
    std::cout << "ID: " << person.first << ", Name: " << person.second << std::endl;

    return 0;
}

In this example, we create an object person of type std::pair<int, std::string>, storing an integer ID and a string name respectively.

Class Type

A class is a blueprint in C++ for defining objects, which can contain data members (attributes) and member functions (methods). Classes can be used to create objects that share the same attributes and behaviors.

#include <iostream>
#include <string>

// Define a Person class
class Person {
public:
    // Constructor
    Person(int id, const std::string& name)
        : m_id(id), m_name(name) {}

    // Member function
    void printInfo() const {
        std::cout << "ID: " << m_id << ", Name: " << m_name << std::endl;
    }

private:
    int m_id; // Data member
    std::string m_name; // Data member
};

int main() {
    // Create a Person object
    Person alice(1, "Alice");

    // Call member function
    alice.printInfo();

    return 0;
}

In this example, we define a Person class with two private data members m_id and m_name, and a public member function printInfo() to print information. Then we create an object alice of type Person and call its printInfo() method.

Memory Model and Namespaces

Memory Model

The C++ memory model primarily concerns how data is stored and managed in memory. C++ provides several different storage methods, each with its specific uses and characteristics:

Automatic Storage:

  • Variables declared inside functions typically use automatic storage.
  • These variables exist within their scope and are destroyed when leaving the scope.
  • The lifetime of automatic storage variables is related to control flow.

Static Storage:

  • Static variables exist throughout the entire program execution.
  • If a static variable is declared inside a function, it is only visible within that function but retains its value across function calls.
  • If a static variable is declared in global scope, it is visible globally but limited to the file where it is declared.

Dynamic Storage (Dynamic Storage or Heap):

  • Dynamic storage is typically allocated and freed using the new and delete operators.
  • The lifetime of these variables is controlled by the programmer and persists until the memory is explicitly freed.
  • Dynamically allocated memory is located on the heap.

Namespaces

Namespaces are a concept introduced in C++ to avoid name conflicts. They allow programmers to organize related identifiers (such as function names, variable names, class names, etc.) together to avoid name conflicts in the global scope.

Defining Namespaces:

Namespaces are defined using the namespace keyword.

namespace MyNamespace {
    int x = 10;
    void myFunction() { /* ... */ }
}

Using Namespaces:

Members in a namespace can be accessed via fully qualified names.

MyNamespace::x;
MyNamespace::myFunction();

You can also use using directives or declarations to introduce individual identifiers or the entire namespace.

using MyNamespace::x;
using namespace MyNamespace;

Default Namespace:

  • The global scope can be considered a default namespace.
  • If no namespace is explicitly defined, all global identifiers are in this default namespace.

Here is a simple example demonstrating how to use namespaces and variables of different storage types:

#include <iostream>

// Namespace definition
namespace Math {
    double pi = 3.14159265358979323846;

    double calculateArea(double radius) {
        return pi * radius * radius;
    }
}

int main() {
    // Use namespace
    using namespace Math;

    // Dynamic storage variable
    int* p = new int(5);
    std::cout << "Dynamic variable: " << *p << std::endl;
    delete p;

    // Static storage variable
    static int s = 10;
    std::cout << "Static variable: " << s << std::endl;

    // Automatic storage variable
    int a = 20;
    std::cout << "Automatic variable: " << a << std::endl;

    // Use function in namespace
    double radius = 5.0;
    std::cout << "Circle area: " << calculateArea(radius) << std::endl;

    return 0;
}
Share your love