#include #include #include #include template std::pair copy_while(InputIt first, InputIt last, OutputIt out, Pred p) { // Iterate through the input range while (first != last && p(*first)) { *out = *first; // Copy the value to the output ++first; // Move to the next input element ++out; // Move to the next output element } // Return the pair of iterators return {first, out}; } std::vector take_while_sum_less_than(std::vector &invec, int n) { std::vector out; int sum = 0; copy_while(invec.begin(), invec.end(), std::back_inserter(out), [&](int &x) -> bool { return (sum += x) < n; }); return out; } int main() { // Sample data std::vector input = {1, 2, 3, 6, 7, 8}; // We will stop copying when we encounter 6 std::vector output; // Define the predicate: copy while the value is <= 5 auto pred = [](int n) { return n <= 5; }; // Call copy_while with the test data auto [new_first, new_out] = copy_while(input.begin(), input.end(), std::back_inserter(output), pred); // Assert that the copied elements are correct (only the first three // elements) std::vector test = std::vector{1, 2, 3}; assert(output == test); // Assert that the iterator returned points to the element that did not // match the predicate (6) assert(*new_first == 6); std::vector v{1, 2, 3}; auto w = take_while_sum_less_than(v, 10); std::cout << "Hello" << std::endl; std::for_each(w.begin(), w.end(), [](int &a) { std::cout << a << " " << std::endl; }); }