From 4bdec39c3522f57816ffe98e7440bcdd4b6709d0 Mon Sep 17 00:00:00 2001 From: Baptiste Wicht Date: Sat, 3 Sep 2016 23:13:14 +0200 Subject: [PATCH] std::find(-if) / std::remove(-if) algorithms --- tstl/include/algorithms.hpp | 54 ++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/tstl/include/algorithms.hpp b/tstl/include/algorithms.hpp index cfece20b..630ef4fb 100644 --- a/tstl/include/algorithms.hpp +++ b/tstl/include/algorithms.hpp @@ -232,7 +232,7 @@ void for_each(Iterator it, Iterator end, Functor func){ } } -template +template T accumulate(Iterator it, Iterator end, T init){ while(it != end){ init = init + *it; @@ -243,6 +243,58 @@ T accumulate(Iterator it, Iterator end, T init){ return init; } +template +Iterator find(Iterator first, Iterator last, const T& value){ + for (; first != last; ++first) { + if (*first == value) { + return first; + } + } + + return last; +} + +template +Iterator find_if(Iterator first, Iterator last, Pred pred) { + for (; first != last; ++first) { + if (pred(*first)) { + return first; + } + } + + return last; +} + +template< typename Iterator, typename T > +Iterator remove(Iterator first, Iterator last, const T& value){ + first = std::find(first, last, value); + + if (first != last){ + for(auto it = first; ++it != last; ){ + if (!(*it == value)){ + *first++ = std::move(*it); + } + } + } + + return first; +} + +template +Iterator remove_if(Iterator first, Iterator last, Pred pred) { + first = std::find_if(first, last, pred); + + if (first != last) { + for (auto it = first; ++it != last;) { + if (!pred(*it)) { + *first++ = std::move(*it); + } + } + } + + return first; +} + template constexpr const T& min(const T& a, const T& b){ return a <= b ? a : b;