搜尋此網誌

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

Offer given

hereby: (in legal documents, etc.) as a result of this statement, and in a way that makes something legal

"Coursing through" means to flow, run, or move rapidly and powerfully, often used for liquids like blood or emotions (joy, fear, adrenaline) moving through the body, or for ideas/energy moving through a system, like news or excitement through people. It implies a strong, energetic, and often unstoppable flow, like water in a stream or a wave of feeling.

skit: a short piece of humorous writing or a performance that makes fun of somebody/something by copying them

deadpan: without any expression or emotion; often pretending to be serious when you are joking

absurd: ridiculously unreasonable, unsound, or incongruous

monologue: a long speech in a play, film, etc. spoken by one actor, especially when alone

wacky: funny in a slightly crazy way

prom: (especially in the US) a formal dance, especially one that is held at a high school

low-key: quiet and not attracting a lot of attention or excitement

pomp: the impressive clothes, decorations, music, etc. and traditional customs that are part of an official occasion or ceremony

dashing: (usually of a man) attractive and full of confidence

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

straggler: a person or an animal that is among the last or the slowest in a group to do something, for example, to finish a race or leave a place

assertion: a statement saying that you strongly believe something to be true

exhilarating: very exciting and great fun

orthodontist: a dentist who treats problems relating to the position of the teeth and jaws

grinding: (of a sound) rough and unpleasant to listen to

vow: to make a formal and serious promise to do something or a formal statement that is true

toggle: to press a key or set of keys on a computer keyboard in order to turn a feature on or off, or to move from one program, etc. to another

subsist: to manage to stay alive, especially with limited food or money

tease: to laugh at somebody and make jokes about them, either in a friendly way or in order to annoy them or make them embarrassed

oddball: behaving in a strange or unusual way

overlook: to fail to see or notice something

bunch: (informal, especially North American English) a large amount of something; a large number of things or people

subroutine: a set of instructions which perform a task within a program

peerless: better than all others of its kind

relentlessly: in a way that continues strongly, without stopping, giving up or getting less strong

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

leapfrog: to get to a higher position or rank by going past somebody else or by missing out some stages

hotshot: a person who is extremely successful in their career or at a particular sport

notion: an idea, a belief or an understanding of something

stature: the importance and respect that a person has because of their ability and achievements

upstart: a person who has just started in a new position or job but who behaves as if they are more important than other people, in a way that is annoying

laud: to praise somebody/something

visionary: original and showing the ability to think about or plan the future with great imagination and intelligence

"Bonneville" refers to the Bonneville Power Administration (BPA), where a teenage Bill Gates and Paul Allen did one of their first major software jobs in 1973, writing code for the power grid's control system for defense contractor TRW.

forgo: to decide not to have or do something that you would like to have or do

nascent: beginning to exist; not yet fully developed


Bill Gates "Source Code"

Online Dictionaries Used:

hk.dictionary.search.yahoo.com

www.oxfordlearnersdictionaries.com

www.merriam-webster.com/dictionary

Google AI overview

2025年12月9日星期二

English with Maggie

Would you do it for me?

比較像在問意願。

Could you do it for me?

比較像在問能力。


Regular verbs +ed 變過去式

used /use-d/ but not /use-凸/

"ed"的三個發音: /id/ /t/ /d/

/t/ /d/ consonants 收尾用 /id/ 相對大聲

wanted: /wan-tid/

needed: /nee-did/

decided: /de-cai-did/


voiced sound:

l, n, r, b, g, m, z

令 vocal cords 震動

called: /call-d/ but not /call-凸/

cleaned: /clean-d/ but not /clean-凸/

offered: /offer-d/ but not /offer-凸/

loved: /love-d/


voiceless sound:

f, s, th, ch, sh, p, k

不令 vocal cords 震動

stopped: /stop-t/ 而不是 /stop-凸/

looked: /look-t/

helped: /help-t/

喀布爾

2025年12月8日星期一

Containers and Adapters

In C++ STL, sequence containers are data structures that store elements in a linear order, allowing sequential access. The main sequence containers are: array, vector, deque, list, and forward_list.

iteration: the process of repeating a mathematical or computing process or set of instructions again and again, each time applying it to the result of the previous stage

dribble (something) (+ adv./prep.) (in football (soccer) and some other sports) to move the ball along with several short kicks, hits or bounces


for (const auto& action : recentActions)

The above line is a range-based for loop in C++.

for → Starts the loop.

const auto& action

    auto deduces the type of each element in recentActions.

    & means we’re iterating by reference (no copy is made).

    const ensures the element cannot be modified inside the loop.

: recentActions → The container we’re iterating over (e.g., std::vector, std::list, etc.).

deduce: to form an opinion about something based on the information or evidence that is available

recentActions is the container (e.g., std::vector, std::list, etc.) that holds multiple elements.

action is a reference to each individual element inside recentActions as the loop iterates.


In C++, std::list is a sequence container implemented as a doubly linked list. It allows fast insertions and deletions anywhere in the sequence but does not support random access like arrays or vectors.


In C++, associative containers are part of the Standard Template Library (STL) that store elements in a way that allows fast retrieval based on keys rather than positions. The main ordered associative containers are: set, multiset, map, and multimap.


Defined in the <set> header as std::set<T>.

Stores unique elements in a sorted order.

Internally implemented as a balanced binary search tree (usually a Red-Black Tree).

Provides logarithmic time complexity (O(log n)) for insertion, deletion, and search.


A side-scrolling video game (alternatively side-scroller) is a video game viewed from a side-view camera angle where the screen follows the player as they move left or right.


The dot (.) operator in C++ is one of the fundamental operators used for member access.

The dot operator (.) is used to access members (variables, functions, or nested types) of an object, struct, or class directly.

It works when you have an object (not a pointer).


The std::pair class in C++ is a simple but powerful utility that lets you store two values together as a single unit. It’s defined in the <utility>  header.

std::pair<std::string, int> playerStats("Alice", 75);

The above line of code is creating a std::pair object named playerStats with two values:

first"Alice" (a std::string)

second75 (an int)


Defined in the <map> header as std::map<Key,T>.

Stores key–value pairs where:

    Key → unique identifier.

    Value (T) → data associated with the key.

Internally implemented as a balanced binary search tree (usually a Red-Black Tree).

Keys are always kept in sorted order (by default using std::less<Key>).


In C++, unordered containers are part of the STL that store elements in hash tables rather than sorted trees. They provide average constant-time (O(1)) performance for insertion, deletion, and lookup, but do not maintain any order of elements.


Container adapters are special containers that provide a restricted interface built on top of other sequence containers (like deque, list, or vector).

They don’t store elements in a unique way themselves; instead, they adapt existing containers to provide specific behaviors.

Defined in the <queue> and <stack> headers.


Last in First out

It’s a data access principle used in computer science and programming.

Think of it like a stack of plates: the last plate you put on top is the first one you take off.

In C++, this principle is implemented using the std::stack container adapter.

empty()

Checks whether the stack has any elements.

top()

Returns a reference to the top element of the stack (the last pushed element).

Does not remove the element.

pop()

Removes the top element from the stack. 


FIFO is the opposite of LIFO (Last In, First Out).

Think of it like a line at a store: the first person to enter the line is the first person served.

In C++, FIFO is implemented using the std::queue container adapter.

front() gives you a reference to the first element in the container.

Does not remove the element (unlike pop() in a queue).

Undefined behavior if called on an empty container (so always check with empty() first).


Defined in the <queue> header as std::priority_queue.

Stores elements in a way that the highest priority element is always accessible at the top.

Internally implemented using a heap structure (by default, a max-heap built on top of a std::vector).

std::priority_queue<int> aiTasks;

std::priority_queue → A priority queue of integers.

aiTasks → The variable name.

By default, std::priority_queue is a max-heap, meaning the largest integer will always be at the top.


In C++ STL, container adapters are special wrappers that provide a specialized interface on top of existing sequence containers (like deque, list, or vector). Instead of exposing all the operations of the underlying container, they restrict and tailor the interface to enforce a particular usage pattern.


Microsoft Copilot