搜尋此網誌

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

1970s Computers in Harvard University

ECL: Extensible Computer Language

LHASA (Logic and Heuristics Applied to Synthetic Analysis) is a computer program developed in 1971 by the research group of Elias James Corey at the Harvard University Department of Chemistry. The program uses artificial intelligence techniques to discover sequences of reactions which may be used to synthesize a molecule. This program was one of the first to use a graphical interface to input and display chemical structures.

idle: ​(of machines, factories, etc.) not in use

The RAND Tablet is a graphical computer input device developed by The RAND Corporation.

stylus: (computing) a special pen used to write text or draw an image on a special computer screen

ubiquitous: seeming to be everywhere or in several places at the same time; very common

Chevrolet is an American automobile division of the manufacturer General Motors.

Digital Equipment Corporation (DEC) using the trademark Digital, was a major American company in the computer industry from the 1960s to the 1990s.

tinker (with something) to make small changes to something in order to repair or improve it, especially in a way that may not be helpful

legendary: very famous and talked about a lot by people

Spawn in computing refers to a function that loads and executes a new child process.

frivolous: ​(of people or their behavior) silly or funny, especially when such behavior is not suitable

snowflake: a small soft piece of frozen water that falls from the sky as snow

groundbreaking: making new discoveries; using new methods

A computer rack is a metal frame that is used to keep different hardware devices such as servers, hard disk drives, modems, and other electronic equipment.

Sketchpad is a computer program written by Ivan Sutherland in 1963 in the course of his PhD thesis.

"By then" is a phrase indicating a point in the future or past that has already been established in the conversation

soup up: (informal) to make changes to something such as a car or computer, so that it is more powerful or exciting than before

harness something to control and use the force or strength of something to produce power or to achieve something

nifty: practical; working well

devise something: to invent something new or a new way of doing something

Xerox PARC (Palo Alto Research Center) is a legendary R&D center by Xerox that invented foundational technologies for modern computing, including the graphical user interface (GUI), mouse, Ethernet, laser printers, bitmap graphics, and object-oriented programming (OOP) (Smalltalk).

PostScript (PS) is a page description language and dynamically typed, stack-based programming language.

cockpit: the area in a plane, boat or racing car where the pilot or driver sits

A baseball pitch is the act of a pitcher throwing the ball to the batter to start a play, varying velocity, movement, and location using different grips (like four-seam fastball, curveball, slider, changeup) to deceive the hitter and get an out.

"Scooping" in baseball is a fielding technique, especially for first basemen, to cleanly catch low throws or ground balls by digging the glove down and "up" to get under the ball, preventing it from going in the dirt.

A pop fly (or pop-up) in baseball is a short, high, arcing batted ball, usually hit to the infield, that doesn't travel far and is often an easy catch for an out, though sometimes dropped due to sun or misjudgment, leading to potential errors.

shortstop: (in baseball) a player who tries to stop balls that are hit between second and third base; the position of this player

aka: also known as

deliberately: done in a way that was planned, not by chance

hype: advertisements and discussion in the media telling the public about a product and about how good or important it is

quirk: a strange thing that happens, especially by accident

de facto: (from Latin, formal) existing as a fact although it may not be legally accepted as existing

subsist (on something) to manage to stay alive, especially with limited food or money

suite: a set of rooms, especially in a hotel

trivia: unimportant matters, details or information

 ALaserDisc (LD) used for music, often featuring music videos, concerts, or high-fidelity audio, predating DVDs, known for its large 12-inch size (like vinyl LPs) and ability to hold both video and high-quality stereo/surround sound

instill: to gradually put an idea or attitude into somebody's mind; to make somebody feel, think or behave in a particular way over a period of time

obsession: the state in which a person’s mind is completely filled with thoughts of one particular thing or person in a way that is not reasonable or normal

mundane: not interesting or exciting

a restaurant where you choose and pay for your meal before you carry it to a table. Cafeterias are often found in factories, colleges, hospitals, etc.

pinball: a game played on a pinball machine, in which the player sends a small metal ball up a sloping board and scores points as it bounces off objects. The player tries to prevent the ball from reaching the bottom of the machine by pressing two buttons at the side.

abortion: the deliberate ending of a pregnancy at an early stage

crook: (informal) a dishonest person

coed: a female student at a co-educational school or college

velvet: ​a type of cloth made from silk, cotton or nylon, with a thick, soft surface

bell-bottoms: trousers with legs that become very wide below the knee

posse: (informal) a group of people who are similar in some way, or who spend time together

if people do or say something in unison, they all do it at the same time

stammer: to speak with difficulty, repeating sounds or words and often stopping, before saying things correctly

bushwhack: To bushwhack means to move through thick, uncleared terrain by cutting a path (like in hiking or exploring)

meld: to combine with something else; to make something combine with something else

congeal: (of blood, fat, etc.) to become thick or solid


Bill Gates "Source Code"

Online Dictionaries Used:

hk.dictionary.search.yahoo.com

www.oxfordlearnersdictionaries.com

Google AI overview

2026年1月6日星期二

Function objects

In C++, a function object (also called a functor) is any object that can be called like a function using the operator(). They are widely used in the Standard Template Library (STL) for algorithms, sorting, and predicates because they can hold state and be passed as types.

- A function object is a class or struct that overloads the operator().
- This allows instances of the class to be used with function-call syntax.
- Unlike normal functions, function objects can store state (data members) and be customized.

In C++, operator overloading allows you to redefine how operators (like +, -, [], (), etc.) behave for user-defined types such as classes and structs. This makes objects act more like built-in types and enables intuitive syntax for complex data structures.

class Point {
    int x, y;
public:
    Point(int a, int b) : x(a), y(b) {}  // Parameterized constructor
    void display() { std::cout << x << ", " << y << std::endl; }
};

1. Data Members
- int x, y; → These represent the coordinates of the point.
- They are private by default (since no access specifier is given before them)

2. Parameterized Constructor
- This constructor takes two arguments (a and b) and initializes x and y.
- The member initializer list (: x(a), y(b)) is the recommended way to initialize members because it’s efficient and works well with const/reference members

3. Member Function
- Prints the point’s coordinates in (x, y) style.

x is a data member (or field) of the class Point.
- It belongs to each object of the class.
- It represents the state of the object (the x-coordinate of the point).
- Stored inside the object itself.

a is a constructor parameter (a local variable passed into the constructor).
- It exists only during the execution of the constructor.
- It is used to initialize the data member x.

How They Work Together
When you write:
Point(int a, int b) : x(a), y(b) {}

- a and b are temporary input values.
- x and y are the persistent attributes of the object.
- The initializer list : x(a), y(b) assigns the values of a and b to the object’s members x and y.
Example:
Point p1(3, 4);
p1.display(); // Output: 3, 4

- Here, a = 3, b = 4 (constructor parameters).
- These values are stored into x = 3, y = 4 (object’s data members).
- After the constructor finishes, a and b disappear, but x and y remain inside p1.

Analogy
Think of it like filling out a form:
- a is the value you write on the form (temporary input).
- x is the information stored in the database (permanent attribute of the object).

Summary:
- x is a member variable of the class (lives as long as the object exists).
- a is a constructor parameter (temporary, exists only while the constructor runs).
- The constructor uses a to initialize x.

MultiplyBy multiplyBy5(5);

1. MultiplyBy → the class name
- This tells the compiler what type of object you want to create.
- In this case, you’re saying: "I want an object of type MultiplyBy."

2. multiplyBy5 → the variable name
- This is the name you’re giving to the object you’re creating.
- You could call it anything: m, functor, timesFive, etc.

3. (5) → the constructor argument
- This passes the value 5 into the constructor of MultiplyBy.
- That sets the private member factor_ to 5.

encapsulate something (in something) to express the most important parts of something in a few words, a small space or a single object

functionality: (computing) the range of functions that a computer or other electronic system can perform

In C++, a std::pair is a simple container that holds two values (often of different types) together as a single unit.

const std::pair<std::string, int>& enemy
- enemy is a reference to a std::pair object.
- No copy of the pair is made — this avoids unnecessary overhead, especially when working with large objects.
- The const ensures you cannot modify the original pair through this reference.

std::sort(enemies.begin(), enemies.end(), SortByHealth());
- Comparator provided: SortByHealth is a functor that defines how two elements should be compared.
- Sorting criterion: In your case, enemies are sorted by their health (second element of the pair).

std::sort(enemies.begin(), enemies.end());
- No comparator provided: std::sort uses the default operator < for the element type.
- Sorting criterion: For std::pair, the default < works lexicographically:
- First compares first (the string name).
- If the names are equal, then compares second (the health).
- Result: Enemies would be sorted alphabetically by name, not by health.

- bool operator() defines the comparison logic.
- std::sort calls this operator repeatedly to decide the order.

A lambda expression is a concise way to define an anonymous function (a function without a name) that can be used where a function is expected, such as an argument to another function or assigned to a variable. They are widely used in many modern programming languages, including Python, Java, C#, and C++, to write cleaner, more readable, and efficient code.

Lambda with Parameters:

#include <iostream>

int main() {
    auto add = [](int a, int b) {
        return a + b;
    };

    std::cout << "Sum: " << add(3, 4) << std::endl;  // Output: 7
}

Using Lambda in Sorting:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> scores = {10, 40, 20, 50, 30};

    // Sort descending using a lambda
    std::sort(scores.begin(), scores.end(),
              [](int a, int b) { return a > b; });

    for (int score : scores)
        std::cout << "Score: " << score << std::endl;
}

Explanation of local scope operations:

#include <iostream>
using namespace std;

int main() {
    int x = 10;  // global to main()

    {
        int y = 20;  // local to this block
        cout << "Inside block: x = " << x << ", y = " << y << endl;
    }

    // y is not accessible here
    // cout << y;  // Error: 'y' was declared in a local scope

    return 0;
}

Microsoft Copilot