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

logical_and ใน C++ STL: ฟังก์ชัน Logical AND แบบ Function Object

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

std::logical_and เป็น **Binary Function Object** ใน <functional> คืนค่า true ก็ต่อเมื่อ **ทั้งสองอาร์กิวเมนต์เป็น true** (Logical AND)

Syntax

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

ตัวอย่างการใช้งาน

#include <bits/stdc++.h>
using namespace std;

int main() {
    bool a[] = {true, false, true, false, true};
    bool b[] = {true, true, false, false, true};
    int n = 5;
    bool out[5];
    
    transform(a, a + n, b, out, logical_and<bool>());
    
    cout << "Logical AND results:\n";
    for (int i = 0; i < n; i++) {
        cout << a[i] << " AND " << b[i] << " = " << out[i] << "\n";
    }
    return 0;
}

Output

Logical AND results:
1 AND 1 = 1
0 AND 1 = 0
1 AND 0 = 0
0 AND 0 = 0
1 AND 1 = 1

การใช้งานทั่วไป

  • std::transform รวมเงื่อนไข 2 array
  • std::accumulate ตรวจสอบ all true
  • Predicate ใน algorithms อื่นๆ

ตัวอย่าง: ตรวจสอบว่าทุกค่าใน vector เป็น true

vector<bool> v = {true, true, true, false};
bool all_true = accumulate(v.begin(), v.end(), true, logical_and<bool>());
// หรือ C++17: reduce(v.begin(), v.end(), true, logical_and<bool>())
// หรือ lambda: all_of(v.begin(), v.end(), [](bool x){ return x; })

Specialization void (C++14)

template <> struct logical_and<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;
};

ฟังก์ชันพี่น้อง

  • logical_or - OR (true ถ้าอย่างน้อย 1 ตัว true)
  • logical_not - NOT (unary)
  • bit_and, bit_or, bit_xor, bit_not - Bitwise operations

สรุป

logical_and เป็น functor สำหรับ logical AND ใช้กับ STL algorithms ได้ แต่วันนี้แนะนำให้ใช้ Lambda แทนเพื่อความอ่านง่ายและประสิทธิภาพ