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

ฟังก์ชัน transform_inclusive_scan() ใน C++


ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อเข้าใจฟังก์ชัน transform_inclusive_scan() ใน C++

ฟังก์ชันนี้ทำการ transform แต่ละองค์ประกอบด้วย unary operation แล้วคำนวณ prefix sum ด้วย binary operation (รวมองค์ประกอบปัจจุบันด้วย)

ตัวอย่างโค้ด

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

namespace point_input_iterator {
    template <class InputIterator, class OutputIterator, class BinaryOperation, class UnaryOperation>
    OutputIterator transform_inclusive_scan(InputIterator first,
                                            InputIterator last,
                                            OutputIterator d_first,
                                            BinaryOperation binary_op,
                                            UnaryOperation unary_op) {
        *d_first = unary_op(*first);
        first++;
        d_first++;
        for (auto it = first; it != last; it++) {
            // คำนวณ prefix sum
            *d_first = binary_op(unary_op(*it), *(d_first - 1));
            d_first++;
        }
        return d_first;
    }
}

int main() {
    // ใส่ข้อมูลด้วย vector
    vector<int> InputVector{ 11, 22, 33, 44, 55, 66, 77, 88 };
    vector<int> OutputVector(8);
    point_input_iterator::transform_inclusive_scan(InputVector.begin(), InputVector.end(), OutputVector.begin(),
        [](auto xx, auto yy) { return xx + yy; },
        [](auto xx) { return xx * xx; });
    for (auto item : OutputVector) {
        cout << item << " ";
    }
    cout << std::endl;
    return 0;
}

เอาต์พุต

121 605 1694 3630 6655 11011 16940 24684