1+ /* *
2+ * Search algorithms
3+ * @author Lobaskin Vasily
4+ * @data 31 March 2020
5+ * @copyright Boost Software License, Version 1.0
6+ */
7+
8+ #pragma once
9+
10+ #include < cstddef>
11+
12+ namespace network {
13+ namespace algorithm {
14+
15+ template <typename IteratorBegT, typename IteratorEndT, typename RangeT>
16+ IteratorBegT find_nth (IteratorBegT iteratorBeg, IteratorEndT iteratorEnd,
17+ RangeT symbol, std::size_t pos) {
18+ static_assert (std::is_same<IteratorBegT, IteratorEndT>::value,
19+ " Iterator types are different" );
20+
21+ if (iteratorBeg > iteratorEnd) {
22+ std::swap (iteratorBeg, iteratorEnd);
23+ }
24+
25+ std::size_t currentPos = -1 ;
26+ while (iteratorBeg != iteratorEnd) {
27+ if (*iteratorBeg == symbol) {
28+ ++currentPos;
29+ if (currentPos == pos) break ;
30+ }
31+ ++iteratorBeg;
32+ }
33+
34+ return iteratorBeg;
35+ }
36+
37+ template <typename IteratorBegT, typename IteratorEndT, typename ConditionT>
38+ bool all (IteratorBegT iteratorBeg, IteratorEndT iteratorEnd,
39+ ConditionT &&condition) {
40+ static_assert (std::is_same<IteratorBegT, IteratorEndT>::value,
41+ " Iterator types are different" );
42+
43+ if (iteratorBeg > iteratorEnd) {
44+ std::swap (iteratorBeg, iteratorEnd);
45+ }
46+
47+ while (iteratorBeg != iteratorEnd) {
48+ if (!condition (*iteratorBeg)) return false ;
49+
50+ ++iteratorBeg;
51+ }
52+
53+ return true ;
54+ }
55+
56+ template <typename ContainerT, typename RangeT>
57+ typename ContainerT::const_iterator find_nth (ContainerT const &str,
58+ RangeT symbol, std::size_t pos) {
59+ return algorithm::find_nth (str.begin (), str.end (), symbol, pos);
60+ }
61+
62+ template <typename ContainerT, typename RangeT>
63+ typename ContainerT::const_iterator find_last (ContainerT const &str,
64+ RangeT symbol) {
65+ auto iter = algorithm::find_nth (str.rbegin (), str.rend (), symbol, 0 );
66+ if (iter == str.rend ()) {
67+ return str.end ();
68+ }
69+
70+ return (++iter).base ();
71+ }
72+
73+ template <typename ContainerT, typename ConditionT>
74+ bool all (ContainerT const &container, ConditionT &&condition) {
75+ return all (container.cbegin (), container.cend (),
76+ std::forward<ConditionT>(condition));
77+ }
78+
79+ } // namespace algorithm
80+ } // namespace network
0 commit comments