搜尋此網誌

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

沒有留言:

發佈留言