Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Modulus Function ใน C++ STL: std::modulus ฟังก์ชันหารเอาเศษ

std::modulus คืออะไร?

std::modulus เป็น **Binary Function Object** (functor) ใน header <functional> ใช้คำนวณเศษจากการหารของอาร์กิวเมนต์ 2 ตัว ทำงานเหมือน operator %

Syntax (C++11/14/17)

template <class T> struct modulus {
    T operator()(const T& a, const T& b) const { return a % b; }
};

Template Parameter

  • T - ประเภทข้อมูล (int, long, double, ฯลฯ)

การใช้งานกับ std::transform

#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;

int main() {
    vector<int> arr = {10, 20, 35, 45, 50, 61};
    vector<int> rem(arr.size());
    
    // หาเศษหาร 2: 0=คู่, 1=คี่
    transform(arr.begin(), arr.end(), rem.begin(), 
              bind(modulus<int>(), placeholders::_1, 2));
              // หรือ C++11 lambda: [](int x){ return x % 2; }
    
    for (size_t i = 0; i < arr.size(); i++) {
        cout << arr[i] << " is " << (rem[i] == 0 ? "even" : "odd") << "\n";
    }
    return 0;
}

Output

10 is even
20 is even
35 is odd
45 is odd
50 is even
61 is odd

ใช้กับ algorithms อื่นๆ

// accumulate with custom binary op (ไม่ค่อยใช้ modulus ตรงนี้)
#include <numeric>
// ...

// count_if กับ modulus
int count_even = count_if(v.begin(), v.end(), 
                          bind(modulus<int>(), placeholders::_1, 2) == 0);
// แนะนำ lambda แทน: [](int x){ return x % 2 == 0; }

Specialization สำหรับ void (C++14)

template <> struct modulus<void> {
    template <class T, class U>
    auto operator()(T&& a, U&& b) const 
        -> decltype(forward<T>(a) % forward<U>(b)) {
        return forward<T>(a) % forward<U>(b);
    }
    using is_transparent = void; // heterogeneous lookup
};

ข้อควรระวัง

  • Modulus กับ negative numbers: C++ truncates toward zero (แตกต่างจาก Python)
  • -5 % 2 == -1 ใน C++
  • สำหรับ floating point ใช้ fmod จาก <cmath> แทน
  • สมัยใหม่แนะนำให้ใช้ **Lambda** แทน bind + modulus เพราะอ่านง่ายกว่าและมีประสิทธิภาพเท่า/ดีกว่า

สรุป

std::modulus เป็น function object สำหรับ % ใช้กับ STL algorithms ได้ แต่วันนี้มักใช้ Lambda แทนเพื่อความชัดเจน