搜尋此網誌

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

Step Pyramid

The Pyramid of Djoser, sometimes called the Step Pyramid of Djoser, is an archaeological site in the Saqqara necropolis, Egypt, northwest of the ruins of Memphis.

en.wikipedia.org and edited

Precocious

rumble: to move slowly and heavily, making a rumbling sound

crate: a large wooden container for transporting goods

dodge: to move quickly and suddenly to one side in order to avoid somebody/something

chant: to sing or shout the same words or phrases many times

ICBM: intercontinental ballistic missile

spin out: to make something last as long as possible

hulking: ​very large or heavy, often in a way that causes you to feel nervous or afraid

The Manhattan Project was a research and development program undertaken during World War II to produce the first nuclear weapons.

hallway: a space or passage inside the entrance or front door of a building

ARPANET: Advanced Research Projects Agency Network

​off-limits (to somebody) (of a place) where people are not allowed to go

domain: ​lands owned or ruled by a particular person, government, etc., especially in the past

stint: a period of time that you spend working somewhere or doing a particular activity

overseer: (old-fashioned) a person whose job is to make sure that other workers do their work

academia: the world of learning, teaching, research, etc. at universities, and the people involved in it

Parliament cigarettes are a premium brand known for their distinctive recessed filter, designed to keep tar and nicotine away from the smoker's lips.

exploit: utilize

arcane: secret and mysterious and therefore difficult to understand

veteran: a person who has a lot of experience in a particular area or activity

A swivel chair is a chair with a single central leg that allows the seat to rotate 360 degrees to the left or right.

spiel: a speech that somebody has used many times that is intended to persuade you to believe something or buy something

exceptionality: it refers to the state of being unusually excellent or rare


Bill Gates "Source Code"

Online Dictionaries Used:

hk.dictionary.search.yahoo.com

www.oxfordlearnersdictionaries.com

2025年12月23日星期二

Iterators

In C++, containers are part of the Standard Template Library (STL). They are class templates that store collections of objects and provide methods to access, insert, and manage them. The main categories are sequence containers, associative containers, and unordered associative containers.

In computer science, traversing means systematically visiting every element in a data structure (like an array, tree, or list) to process or use its data, often with loops or recursion.

recursion: the process of repeating a function, each time applying it to the result of the previous stage

In C++, iterators are pointer-like objects used to traverse containers (like vector, list, map) and access their elements. They provide a uniform way to loop through different container types without worrying about their internal structure.

Pointers are one particular type of iterators. Pointers are not just memory addresses; in the STL world, they are treated as the simplest and most efficient iterators.

A pointer is a variable that stores the memory address of another variable. It can be reassigned to point to different variables.

#include <iostream>

using namespace std;


int main() {

    int x = 10;


    // Declare a pointer to int

    int* ptr = &x;   // ptr stores the address of x


    cout << "Value of x: " << x << endl;

    cout << "Address of x: " << &x << endl;

    cout << "Pointer ptr holds: " << ptr << endl;

    cout << "Value at ptr (dereference): " << *ptr << endl;


    // Modify x using the pointer

    *ptr = 20;

    cout << "New value of x: " << x << endl;


    return 0;

}


Output:

Value of x: 10

Address of x: 0x7ffee3b8c8ac   // (example address, varies)

Pointer ptr holds: 0x7ffee3b8c8ac

Value at ptr (dereference): 10

New value of x: 20


References must always refer to a valid object (cannot be null).

alias: used when a person, especially a criminal or an actor, is known by two names

#include <iostream>

using namespace std;


void addFive(int& ref) {

    // ref is a reference to the original variable

    ref = ref + 5;

}


int main() {

    int x = 10;


    // Create a reference to x

    int& alias = x;


    cout << "Original x = " << x << endl;

    cout << "Reference alias = " << alias << endl;


    // Modify x through the reference

    alias = 20;

    cout << "After alias change, x = " << x << endl;


    // Pass by reference to a function

    addFive(x);

    cout << "After function call, x = " << x << endl;


    return 0;

}


Result:

Original x = 10

Reference alias = 10

After alias change, x = 20

After function call, x = 25


void addFive(int& ref)

void → The function doesn’t return a value.

addFive → The function’s name.

int& ref → The parameter is a reference to an integer.

This means the function receives an alias to the caller’s variable.

Any changes made to ref inside the function directly affect the original variable


C++ defines five main categories of iterators: input, output, forward, bidirectional, and random access. Each category specifies what operations are allowed (reading, writing, moving forward/backward, jumping).

int x;

cin >> x;   // read a number from the keyboard into x


int y = 42;

cout << y;   // write the number 42 to the screen


begin()

returns an iterator to the first element of the container.

end()

returns an iterator to one past the last element of the container.

It does not point to the last element itself, but to a position just beyond it.

rbegin()

returns a reverse iterator to the last element of the container.

rend()

returns a reverse iterator to one before the first element.


Microsoft Copilot

collaboration

devil's advocate: someone who pretends, in an argument or discussion, to be against an idea or plan that a lot of people support, in order to make people discuss and consider it in more detail

tempt: to attract somebody or make somebody want to do or have something, even if they know it is wrong

In the U.S., graduate school means pursuing advanced education after a bachelor's degree.

stack up: to compare with somebody/something else; to be as good as somebody/something else

proverbial: well known and talked about by a lot of people

profound: very great; felt or experienced very strongly

modest: not very large, expensive, important, etc.

theorem: DJ[ˋθiərəm] a rule or principle, especially in mathematics, that can be proved to be true

hatch: to create a plan or an idea, especially in secret

far-fetched: very difficult to believe

grist: useful ideas or material

collaboration: the act of working with another person or group of people to create or produce something

simplistic: making a problem, situation, etc. seem less difficult or complicated than it really is

backdrop: everything that can be seen around an event or scene

shoot down: to be very critical of somebody’s ideas, opinions, etc.

spat: (informal) a short argument about something unimportant

parking lot: ​(North American English) an area where people can leave their cars

Mustang has been representing the classic American muscle car since 1964, powerful engine and astonishing performance brings you the sense of speed.

Chrysler is a historic American automotive brand.

whatever: any or every; anything or everything

make a beeline for something/somebody: (informal) to go straight towards something/somebody as quickly as you can

string: to hang or tie something in place

haste: speed in doing something, especially because you do not have enough time

whoosh: a soft sound made by something moving fast through air or like that made when air is pushed out of something

slingshot: ​a stick that has the shape of a Y with a rubber band attached to it, used by children for shooting stones

pavement: a flat part at the side of a road for people to walk on

amble: to walk at a slow relaxed speed

grate: to annoy somebody

venture: a business project or activity, especially one that involves taking risks

conviction: a strong opinion or belief

meantime: meanwhile

rivalry: a state in which two people, companies, etc. are competing for the same thing

temperament: a person’s or an animal’s nature as shown in the way they behave or react to situations or people

detente: an improvement in the relationship between two or more countries which have been unfriendly towards each other in the past


Bill Gates "Source Code"

Online Dictionaries Used:

hk.dictionary.search.yahoo.com

www.oxfordlearnersdictionaries.com

dictionary.cambridge.org/dictionary

2025年12月16日星期二

Queues and Stacks

Queue (FIFO)

  • Definition: A queue is a linear data structure that follows the First In, First Out (FIFO) principle.
  • Analogy: Think of people lining up at a ticket counter. The first person to join the line is the first to be served.
#include <iostream>
#include <queue>
using namespace std;

int main() {
    queue<int> q;

    // Enqueue elements into the queue
    q.push(10);
    q.push(20);
    q.push(30);

    cout << "Queue (FIFO):" << endl;
    while (!q.empty()) {
        cout << q.front() << " ";  // Access the front element
        q.pop();                   // Remove the front element
    }
    return 0;
}

while (!q.empty())
q → This is your queue object (e.g., queue q;).
q.empty() → This function returns true if the queue has no elements, otherwise false.
!q.empty() → The ! (logical NOT) operator flips the result:
If the queue is not empty, !q.empty() is true.
If the queue is empty, !q.empty() is false.
while (!q.empty()) → This loop continues to run as long as the queue has elements inside.

Stack (LIFO)

  • Definition: A stack is a linear data structure that follows the Last In, First Out (LIFO) principle.
  • Analogy: Imagine a stack of plates. The last plate placed on top is the first one you take off.
#include <iostream>
#include <stack>
using namespace std;

int main() {
    stack<int> s;

    // Push elements onto the stack
    s.push(10);
    s.push(20);
    s.push(30);

    cout << "Stack (LIFO):" << endl;
    while (!s.empty()) {
        cout << s.top() << " ";  // Access the top element
        s.pop();                 // Remove the top element
    }
    return 0;
}

Microsoft Copilot