搜尋此網誌

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

Lilas × marasy - Koikaze


The aftereffects of a past love

Left me unable to move forward

At times it aches and throbs (陣陣作痛)

Making me fearful

But you ---

With eyes so dazzlingly (燦爛地) bright

Gazed straight into me

And the hands of my inner clock started once more

Lightly

Softly into an empty heart

You leapt (越過) like a breeze (微風)

It’s like

I want to keep being swept away

Might as well take me

Far, far away

Spilling (溢出) over

Like the leaves of trees

My heart finds its way to you

Dancing in the air, fluttering (拍動)

Back and forth

How do I appear in those eyes of yours?

Swirling (旋轉) round and round

As if my temperature’s rising

Softly, in an unclear heart

Budding feelings emerge

And I waver

If I yield myself to the moment

And jump in

Wondering what you are doing

Or where or who you are laughing with

Wanting to see you

When I see something beautiful

It makes me want to share it with you

These frustrating feelings are

Falling in love

Should be more simple

My feelings

That sparkle like a flash of light

I hold them tight and carry on

In this moment

I can ride on the wind you stirred

Steadily taking

The first step forward

“I love you”

Maths course in Harvard

a person of color: generally refers to anyone who is not White or of European descent, encompassing diverse racial and ethnic groups like Black, Asian, Native American, Pacific Islander, and mixed-race individuals

Montreal is the largest city in the province of Quebec, the second-largest in Canada, and the eighth-largest city in North America.

Tennessee: a landlocked state in the Southeastern region of the United States.

upbringing: ​the way in which a child is cared for and taught how to behave while it is growing up

janitor: a person whose job is to take care of a building such as a school or a block of flats or an apartment building

horde: ​a large crowd of people

dorm: dormitory

tuition: the money that you pay to be taught, especially in a college or university

the Holocaust: the killing of millions of Jewish people by the German Nazi government in the period 1941–1945

insular: having little contact with other people

goofy: silly; stupid

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

Ulysses: a novel (1922) by James Joyce. It is considered by many people to be one of the greatest novels of the 20th century, although it was not published in Britain and the US until the 1930s because it was thought to be too offensive. It is written in a wide variety of styles, and deals with the events of one day through the experiences of three main characters, Stephen Dedalus, Leopold Bloom and Molly Bloom.

Antigone appears in three 5th century BC tragic plays written by Sophocles, known collectively as the three Theban plays, with her being the protagonist of the eponymous tragedy Antigone.

legendary: very famous and talked about a lot by people

open-ended: without any limits, aims or dates fixed in advance

prominent: easily seen

prospective: potential

prestigious: respected and admired as very important or of very high quality

frizzy: (of hair) not smooth and neat but very curly and untidy

smudge (something) to touch or rub something, especially wet ink or paint, so that it is no longer clear; to become not clear in this way

squeak: to make a short high sound that is not very loud

axiom: a rule or principle that most people believe to be true

In mathematics, a tuple is a finite sequence or ordered list of numbers or, more generally, mathematical objects, which are called the elements of the tuple.

In mathematics, an isomorphism is a structure-preserving, one-to-one mapping (a bijective function) between two mathematical structures (like sets, groups, or rings) that shows they are essentially the same in form or structure, even if their elements are different.

acquaintance with something (formal) knowledge of something

heck: ​used to show that you are slightly annoyed or surprised; used to emphasize something

A Banach space is a complete normed vector space, meaning it's a vector space where you can measure vector lengths (norm) and distances, and every Cauchy sequence of vectors converges to a limit that is also within the space.

Topology is a branch of mathematics studying properties of spaces that remain unchanged under continuous deformations like stretching, bending, and twisting, but not tearing or gluing, often called "rubber-sheet geometry".

The Putnam Competition is a prestigious, challenging annual math contest for undergraduate students in the US and Canada, testing creative problem-solving in calculus, linear algebra, and discrete maths.

A vexing problem is a difficult, annoying, puzzling, or worrying issue that is hard to solve, causing frustration and distress.

preternatural: that does not seem natural; that cannot be explained by natural laws

indispensable: essential

team up: ​to join with another person or group in order to do something together

cull: to kill a number of wild animals from a group, especially in order to stop the group from becoming too large

Minnesota is a state in the Upper Midwestern region of the United States.

quad: an open square area that has buildings all around it, especially in a school or college

shriek: to give a loud high shout, for example when you are excited, frightened or in pain


Bill Gates "Source Code"

Online Dictionaries Used:

hk.dictionary.search.yahoo.com

www.oxfordlearnersdictionaries.com

2026年1月2日星期五

Algorithms in computer science

An algorithm is a finite, step-by-step set of instructions or rules designed to solve a specific problem or perform a computation, widely used in math, computer science, and everyday life, acting like a recipe with precise steps to take inputs and produce a desired output. In computing, algorithms power everything from sorting data and running search engines to recommending content on social media, acting as the core logic for software and automated decisions.

for (... : items)
This is a range-based for loop (introduced in C++11).

#include <iostream>
#include <vector>
#include <algorithm>  // for std::sort

int main() {
    std::vector<int> numbers = {5, 2, 9, 1, 5, 6};

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

    for (int n : numbers)
        std::cout << n << " ";
}

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

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

    auto it = std::find(v.begin(), v.end(), 30);

    if (it != v.end())
        std::cout << "Found: " << *it << std::endl;
    else
        std::cout << "Not found" << std::endl;
}

std::find algorithm in C++ (from ) searches for the first occurrence of a given value in a range.


What *it Means
- In C++, iterators behave like pointers.
- it itself is an iterator object (not the actual element).
- Using *it dereferences the iterator, giving access to the element it points to.

it → an iterator pointing to the element 20.
*it → the actual value stored at that position (20).

Why Not Just Use it?
- it is not the element, it’s a “cursor” pointing to the element.
- Printing it directly won’t give the value; it would try to print the iterator object (which usually doesn’t make sense).
- You need *it to access the contents.

Analogy
Think of an iterator like a TV remote:
- The remote (it) points to a channel.
- Dereferencing (*it) is like pressing the button to actually watch the channel.

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

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

    int c = std::count(v.begin(), v.end(), 2);

    std::cout << "Number of 2s: " << c << std::endl;
}

Microsoft Copilot

Revision

In C++, void means “no type”. It’s commonly used to declare functions that don’t return a value, functions that take no parameters

void greet() {
    std::cout << "Hello, World!" << std::endl;
}

Here, greet() performs an action but doesn’t return anything.

In C++, the statement return 0; is most commonly seen in the main() function.

Return value of main():

By convention, returning 0 from main() indicates that the program executed successfully.

Any non-zero value usually signals an error or abnormal termination.

If you omit return 0; in main(), modern C++ standards (C++11 and later) automatically assume return 0; at the end of main().

What \n Does

  • It tells the program to move the cursor to the next line when printing text.
  • Commonly used in std::cout statements to format output.

x += 3;   // equivalent to: x = x + 3;

In modern C++ (since C++11), the keyword auto tells the compiler to automatically deduce the type of a variable or function return value from its initializer or expression.

int i {};   // i is initialized to 0

Explanation

  • This is uniform initialization (introduced in C++11).
  • The curly braces {} tell the compiler to value-initialize the variable.
  • For fundamental types like int, value-initialization sets it to zero.

    • while (std::cin >> score && score != -1)

    • && (Logical AND)

    • Both conditions must be true for the loop to continue;
    • Input must succeed.
    • The value must not be -1.
Microsoft Copilot