dump
This commit is contained in:
commit
5626d1eacb
24 changed files with 512 additions and 0 deletions
6
takewhile/Makefile
Normal file
6
takewhile/Makefile
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
TARGET = takewhile.elf
|
||||
SRCS = takewhile.cc
|
||||
|
||||
all: $(TARGET)
|
||||
|
||||
include ../config.mk
|
||||
54
takewhile/takewhile.cc
Normal file
54
takewhile/takewhile.cc
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
#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; });
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue