File: algorithm.hpp

package info (click to toggle)
openmw 0.50.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 37,076 kB
  • sloc: cpp: 380,958; xml: 2,192; sh: 1,449; python: 911; makefile: 26; javascript: 5
file content (58 lines) | stat: -rw-r--r-- 1,588 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#ifndef OPENMW_COMPONENTS_MISC_ALGORITHM_H
#define OPENMW_COMPONENTS_MISC_ALGORITHM_H

#include <iterator>
#include <type_traits>

#include <components/misc/strings/algorithm.hpp>

namespace Misc
{
    template <typename Iterator, typename BinaryPredicate, typename Function>
    inline Iterator forEachUnique(Iterator begin, Iterator end, BinaryPredicate predicate, Function function)
    {
        static_assert(
            std::is_base_of_v<std::forward_iterator_tag, typename std::iterator_traits<Iterator>::iterator_category>);
        if (begin == end)
            return begin;
        function(*begin);
        auto last = begin;
        ++begin;
        while (begin != end)
        {
            if (!predicate(*begin, *last))
            {
                function(*begin);
                last = begin;
            }
            ++begin;
        }
        return begin;
    }

    /// Performs a binary search on a sorted container for a string that 'key' starts with
    template <typename Iterator, typename T>
    static Iterator partialBinarySearch(Iterator begin, Iterator end, const T& key)
    {
        const Iterator notFound = end;

        while (begin < end)
        {
            const Iterator middle = begin + (std::distance(begin, end) / 2);

            int comp = Misc::StringUtils::ciCompareLen((*middle), key, (*middle).size());

            if (comp == 0)
                return middle;
            else if (comp > 0)
                end = middle;
            else
                begin = middle + 1;
        }

        return notFound;
    }

}

#endif