搜尋此網誌

2026年1月20日星期二

Open a txt file for reading

reading file: ifstream (input file stream)

writing file: ofstream (output file stream)

eof() in C++ is a member function of file stream classes (ifstream, ofstream, fstream) that stands for end-of-file.

stoi in C++ stands for "string to integer".


Meaning of letter = str[0];

  • str → a std::string object.
    • [0] → accesses the first character of the string (indexing starts at 0).
    • letter → a variable of type char that stores the result.

    So this statement assigns the first character of the string str to the variable letter


    Microsoft Copilot

    成長

    hype: to advertise something a lot and make its good qualities seem better than they actually are, in order to get a lot of public attention for it

    conglomerate: (business) a large company formed by joining together different firms

    off base: (North American English, informal) completely wrong about something

    blurt out: say something suddenly, impulsively, and without thinking, often revealing a secret or a thought you intended to keep hidden, typically due to excitement or nervousness, and sometimes leading to regret

    flaw: a mistake in something that means that it is not correct or does not work correctly

    fluster: to make somebody nervous and/or confused, especially by giving them a lot to do or by making them hurry

    dumb: (especially North American English, informal) stupid

    stalk: to walk in an angry or proud way

    dread: to be very afraid of something; to fear that something bad is going to happen

    congenial: (of a person) pleasant to spend time with because their interests and character are similar to your own

    comeuppance: ​a punishment for something bad that you have done, that other people feel you really deserve

    cringe: to feel very embarrassed and uncomfortable about something


    Bill Gates "Source Code"

    Online Dictionaries Used:

    hk.dictionary.search.yahoo.com

    www.oxfordlearnersdictionaries.com

    2026年1月16日星期五

    Working with files

    In C++, the fstream class (from the header) is used for both reading and writing files. It combines the functionality of ifstream (input file stream) and ofstream (output file stream), allowing you to open a file and perform input/output operations on it.

    The is_open() function in C++ is a member of the file stream classes (ifstream, ofstream, and fstream). It is used to check whether a file stream is currently associated with (and successfully opened) a file.

    getline() in C++ — it’s one of the most useful functions for reading text input, especially when dealing with files or user input that includes spaces.

    #include <iostream>

    #include <string>

    using namespace std;


    int main() {

        string name;

        cout << "Enter your full name: ";

        getline(cin, name);  // reads entire line including spaces

        cout << "Hello, " << name << "!" << endl;

        return 0;

    }


    ios::app is a file open mode flag used with file streams (ofstream, fstream).

    Meaning: Append mode.

    When you open a file with ios::app, all output operations are performed at the end of the file, preserving existing content.

    The file pointer is moved to the end before each write.

    Existing data is not erased.


    console: a flat surface that contains all the controls and switches for a machine, a piece of electronic equipment, etc.


    ios::in

    • Meaning: Open file for input (reading).
    • Behavior:
      • The file must exist; otherwise, opening fails.
      • You can read data from the file using the stream.
    • Typical use: Used with ifstream or fstream.

    ios::out

    • Meaning: Open file for output (writing).
    • Behavior:
      • If the file exists, its contents are truncated (erased) unless combined with ios::app.
      • If the file doesn’t exist, it is created.
      • You can write data into the file.
    • Typical use: Used with ofstream or fstream.


    The .close() function in C++ is used with file stream objects (ifstream, ofstream, fstream) to close an open file.


    Microsoft Copilot

    Precocious

    sophomore: a student in the second year of a course of study at a college or university

    audit something (North American English) to attend a course at college or university but without taking any exams or receiving credit

    enthuse: to talk in an enthusiastic and excited way about something

    precocious: (of a child) having developed particular abilities and ways of behaving at a much younger age than usual

    complimentary: expressing approval, praise, etc.

    brat: a person, especially a child, who behaves badly

    dejected: unhappy and disappointed

    stunned: very surprised or shocked; showing this

    propriety: moral and social behavior that is considered to be correct and acceptable

    conversant: moral and social behavior that is considered to be correct and acceptable

    whizz: to do something very quickly

    innate: ​(of a quality, feeling, etc.) that you have when you are born

    subtly: in a way that is not very obvious or easy to notice

    nerd: ​a person who is boring, stupid and not fashionable

    stark: unpleasant; real, and impossible to avoid

    deception: the act of deliberately making somebody believe something that is not true

    hands-down: easily the winner of a contest; definitely the one that people prefer

    suite: a set of rooms, especially in a hotel

    confide: to tell somebody secrets and personal information that you do not want other people to know

    epiphany: a sudden and surprising moment of understanding

    implicit: suggested without being directly expressed

    vibe: a mood or an atmosphere produced by a particular person, thing or place

    prod: to try to make somebody do something, especially when they are unwilling

    languish: to be forced to stay somewhere or suffer something unpleasant for a long time

    scrawl: to write something in a careless untidy way, making it difficult to read

    vocation: a type of work or way of life that you believe is especially suitable for you

    dicey: dangerous and uncertain


    Bill Gates "Source Code"

    Online Dictionaries Used:

    hk.dictionary.search.yahoo.com

    www.oxfordlearnersdictionaries.com

    2026年1月13日星期二

    Chapter Quiz

    A class template allows you to define a class that can work with any data type. Instead of writing separate classes for int, double, string, etc., you write one generic class and let the compiler generate the specific version when you use it

    Inheritance allows one class (the derived class) to reuse and extend the functionality of another class (the base class).

    Polymorphism means “many forms” — the ability of different classes to be treated through a common interface, often using virtual functions.

    In C++ (and in object-oriented programming generally), a superclass is simply another name for a base class — the class that is being inherited from.

    A constructor is a special member function that is automatically called when an object of a class is created.

    A destructor is a special member function that is automatically called when an object goes out of scope or is deleted.


    template <typename T>

    size_t size_in_bits(const T& a) {

        return sizeof(a) * 8;

    }

    template <typename T>

    Declares a function template that can accept any type T.

    const T& a

    The function takes a constant reference to an object of type T.

    Using const ensures the function doesn’t modify a.

    Using a reference avoids copying large objects.

    sizeof(a)

    Returns the size of the object a in bytes.

    * 8

    Converts bytes into bits (since 1 byte = 8 bits).

    Return type size_t

    A standard unsigned integer type used for sizes.


    Queue (FIFO — First In, First Out)

    • Think of a line at a ticket counter: the first person to arrive is the first person served.
    • Operations:
      • Enqueue → add an element at the back.
      • Dequeue → remove an element from the front.

    Stack (LIFO — Last In, First Out)

    • Think of a stack of plates: the last plate you put on top is the first one you take off.
    • Operations:
      • Push → add an element on top.
      • Pop → remove the top element.


    What is std::map?

    • A sorted associative container in the C++ Standard Library.
    • Stores elements as key–value pairs (std::pair).
    • Keys are unique (no duplicates).
    • Internally implemented as a balanced binary search tree (usually a Red-Black Tree).
    • Provides logarithmic time complexity (O(log n)) for insert, search, and delete operations.


    What is std::vector?

    • A sequence container that stores elements in a contiguous memory block (like an array).
    • Unlike arrays, vectors can grow or shrink dynamically.
    • Provides random access to elements (constant time O(1) for indexing).
    • Efficient insertion/removal at the end (push_back, pop_back are amortized O(1)), but slower at the front or middle (O(n)).
    contiguous: touching or next to something

    What is std::list?

    • A sequence container that stores elements in a doubly linked list.
    • Unlike std::vector, elements are not stored contiguously in memory.
    • Provides fast insertion and deletion anywhere in the list (O(1) if you already have the iterator).
    • Slower random access (O(n)), since you must traverse nodes sequentially.

     What is std::priority_queue?

    • A container adapter in the C++ Standard Library.
    • Works like a queue, but instead of FIFO order, it always keeps the largest (or highest priority) element at the front by default.
    • Internally implemented using a heap (usually a max-heap).
    • Provides logarithmic time complexity (O(log n)) for insertion and removal, and constant time O(1) for accessing the top element.

    Pointer

    • A pointer is a variable that stores the memory address of another variable.
    • You can use it to directly access and manipulate memory.
    int x = 10;
    int* p = &x;   // p points to x
    cout << *p;    // dereference → prints 10

    *p → dereference (access value at address).
    &x → address-of operator.
    Pointers can be incremented/decremented to move through contiguous memory (like arrays).

    Iterator

    • An iterator is an object that behaves like a pointer but is designed to work with STL containers (vector, list, map, etc.).
    • Provides a uniform way to traverse containers without worrying about their internal structure.
    In computer science, traversing means systematically visiting or accessing every element in a data structure (like an array, tree, or graph) to process it, often using loops or specific algorithms.

    #include <vector>
    #include <iostream>
    using namespace std;

    int main() {
        vector<int> v = {1, 2, 3, 4};

        // Iterator
        vector<int>::iterator it;
        for (it = v.begin(); it != v.end(); ++it) {
            cout << *it << " ";  // dereference iterator
        }
    }

    begin() → returns iterator to first element.
    end() → returns iterator past the last element.
    Iterators can be incremented (++it) to move forward.
    Some iterators support random access (like pointers in vector), while others only support sequential traversal (like in list).

    Operator overloading in C++ lets you redefine how operators (like +, -, ==, [], etc.) behave for your own classes. It’s a powerful way to make user-defined types feel natural and intuitive to use.

    Normally, operators work with built-in types (int, double, etc.).

    With operator overloading, you can extend them to work with objects.

    Example: Adding two Complex numbers with + instead of writing a function like add(c1, c2).

    Complex numbers are numbers of the form a+bi, where a is the real part, b is the imaginary part, and i is the imaginary unit defined by i^2=-1. They extend the real number system to allow solutions to equations like x^2+1=0, which have no real solutions.


    Microsoft Copilot

    competition among elite

    dazzle: dazzle (somebody) if a strong light dazzles you, it is so bright that you cannot see for a short time

    camaraderie: a feeling of friendship and trust among people who work or spend a lot of time together

    footing: the basis on which something is established or organized

    excel: to be very good at doing something

    outlier: a person or thing that is different from or in a position away from others in the group

    awkward: difficult to deal with

    nudge: a slight push, usually with the elbow

    premed: (especially North American English) a course or set of classes that students take in preparation for medical school

    intently: with strong interest and attention

    monstrous: very large

    agilely: (of the way someone or something moves) quickly and easily

    intimidating: ​frightening in a way that makes a person feel less confident

    crammer: ​a school or book that prepares people quickly for exams

    maniacal: ​wild or violent

    gobble: to eat something very fast, in a way that people consider rude or greedy

    preoccupied: thinking and/or worrying continuously about something so that you do not pay attention to other things

    dingy: dark and dirty

    grimy: ​covered with dirt

    stunned: ​very surprised or shocked; showing this

    screwed: in very bad trouble or difficulty


    Bill Gates "Source Code"

    Online Dictionaries Used:

    hk.dictionary.search.yahoo.com

    www.oxfordlearnersdictionaries.com

    dictionary.cambridge.org

    2026年1月9日星期五

    Learn from exercise

    std::deque (short for double-ended queue) is a container in C++ that allows fast insertion and deletion at both ends. It’s part of the Standard Template Library (STL).

    contiguous: touching or next to something

    #include <deque>
    #include <iostream>
    using namespace std;

    int main() {
        deque<int> dq;

        // Add elements
        dq.push_back(10);   // [10]
        dq.push_front(20);  // [20, 10]

        // Access elements
        cout << dq.front() << endl; // 20
        cout << dq.back() << endl;  // 10
        cout << dq[1] << endl;      // 10

        // Remove elements
        dq.pop_front(); // [10]
        dq.pop_back();  // []

        return 0;
    }

    dq[1] means "give me the element at index 1".

    Since C++ uses zero-based indexing, dq[0] is the first element, and dq[1] is the second element.

    ​intimidate somebody (into something/into doing something) to frighten or threaten somebody so that they will do what you want

    In C++, template is used to define generic functions or classes, while typename clarifies that a dependent name inside a template refers to a type.

    template <typename T>
    T add(T a, T b) {
        return a + b;
    }

    enum class in C++ is a strongly typed enumeration introduced in C++11. It improves upon traditional enum by providing better type safety and scoping.

    #include <iostream>
    using namespace std;

    enum class Color { Red, Green, Blue };
    enum class Fruit { Apple, Banana, Orange };

    int main() {
        Color c = Color::Red;
        Fruit f = Fruit::Apple;

        // Scoped access
        cout << (c == Color::Red) << endl;   // true
        cout << (f == Fruit::Banana) << endl; // false

        // No implicit conversion to int
        // int x = c; // ❌ Error

        // Explicit cast required
        int x = static_cast<int>(Color::Green); // ✅ Works
        cout << x << endl; // prints 1
    }

    In C++, the operator == is the equality comparison operator.

    It checks whether two values are equal.
    Returns a boolean (true or false).

    The symbol :: in C++ is called the scope resolution operator. It’s used to specify the scope in which a name (variable, function, class, etc.) is defined.

    Main Uses of ::

    1. Accessing Global Variables
    If a local variable shadows a global one, :: lets you access the global version:
    #include <iostream>
    using namespace std;

    int x = 10; // global

    int main() {
        int x = 20; // local
        cout << x << endl;   // prints 20
        cout << ::x << endl; // prints 10 (global x)
    }

    2. Accessing Class Members
    Used to define or access members outside the class body:
    class MyClass {
    public:
        static int value;
        void show();
    };

    int MyClass::value = 42; // define static member

    void MyClass::show() {   // define member function
        std::cout << "Value = " << value << std::endl;
    }

    3. Accessing Namespaces
    Used to access functions, classes, or variables inside a namespace:
    #include <iostream>
    namespace Math {
        int add(int a, int b) { return a + b; }
    }

    int main() {
        std::cout << Math::add(3, 4) << std::endl; // 7
    }

    4. Enumerations
    With enum class, you must use :: to access enumerators:
    enum class Color { Red, Green, Blue };

    Color c = Color::Red; // scoped access

    In programming, a dummy value usually means a placeholder value that doesn’t carry real meaning but is used temporarily.

    #include is a C++ standard library header that provides a collection of utility functions, classes, and templates commonly used in generic programming.

    Here is one of the most important components:

    std::pair

    • A simple container that holds two values.
    • Useful for returning two results from a function or storing key-value pairs.
    for (initialization; condition; update) {
        // code to execute repeatedly
    }

    Let’s combine a for loop with a switch statement in C++. This is a common pattern when you want to iterate through values and perform different actions depending on the case.

    #include <iostream>
    using namespace std;

    int main() {
        // Loop from 1 to 5
        for (int i = 1; i <= 5; i++) {
            switch (i) {
                case 1:
                    cout << "Case 1: Hello" << endl;
                    break; // exit switch

                case 2:
                    cout << "Case 2: World" << endl;
                    break;

                case 3:
                    cout << "Case 3: Foo" << endl;
                    break;

                case 4:
                    cout << "Case 4: Bar" << endl;
                    break;

                default:
                    cout << "Default case: i = " << i << endl;
                    break;
            }
        }
        return 0;

    - The for loop runs from i = 1 to i = 5.
    - Each iteration enters the switch block.
    - The case labels match specific values of i.
    - The break ensures the program exits the switch after executing one case (otherwise it would “fall through” to the next case).
    - The default handles values not explicitly (clearly or directly, so that the meaning is easy to understand) listed in cases.

    Case 1: Hello
    Case 2: World
    Case 3: Foo
    Case 4: Bar
    Default case: i = 5

    - break inside switch only exits the switch, not the for loop.
    - If you want to exit the entire loop from inside a switch, you can use break with a label (C++20) or goto, or simply return if inside main.

    for (const auto& op : operations) {
        // use op here
    }

    - operations → a container (like std::vector, std::deque, std::list, etc.).
    - op → each element in the container, one at a time.
    - auto& → deduces the element type automatically and binds it by reference (so no copy is made).
    - const → ensures you cannot modify the element inside the loop.

    if (!schedule.empty())

    - schedule → some container (like std::vector, std::deque, std::list, std::map, etc.).
    - .empty() → a member function that returns true if the container has no elements, false otherwise.
    - ! → logical NOT operator, flips the result.
    So the condition means:
     “If schedule is NOT empty, then execute the following block.

    Microsoft Copilot