cpp_prac/takewhile/takewhile.cc

55 lines
1.8 KiB
C++
Raw Permalink Normal View History

2025-01-10 08:15:31 +01:00
#include <cassert>
#include <iostream>
#include <iterator>
#include <vector>
template <typename InputIt, typename OutputIt, typename Pred>
std::pair<InputIt, OutputIt> 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<int> take_while_sum_less_than(std::vector<int> &invec, int n) {
std::vector<int> 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<int> input = {1, 2, 3, 6,
7, 8}; // We will stop copying when we encounter 6
std::vector<int> 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<int> test = std::vector<int>{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<int> 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; });
}