example5_copying_with_custom_output_iterator.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <vector>
#include <algorithm>

class DoubleOutputIterator {
    int* ptr;
public:
    DoubleOutputIterator(int* p) : ptr(p) {}
    DoubleOutputIterator& operator*() { return *this; }
    DoubleOutputIterator& operator++() { ++ptr; return *this; }
    DoubleOutputIterator operator++(int) { DoubleOutputIterator tmp = *this; ++ptr; return tmp; }
    DoubleOutputIterator& operator=(int value) { *ptr = value * 2; return *this; }
};

int main() {
    std::vector<int> source = {1, 2, 3, 4, 5};
    std::vector<int> destination(5);

    std::copy(source.begin(), source.end(), DoubleOutputIterator(destination.data()));

    std::cout << "Destination vector (doubled values): ";
    for (const auto& num : destination) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}
Back to std_copy