c++ - Is there a function that is to std::search what std::count is to std::find? -
if title sounds weird here explanation:
if have range a, , want count how many times range b appeared in range a, there std::
function it?
if no, there simple way (ofc can manually loop using std::search
- i'm talking more elegant)?
i think you'll need build own. here's comes mind implementation.
template <typename iterator1, typename iterator2> size_t subsequence_count(iterator1 haystack_begin, iterator1 haystack_end, iterator2 needle_begin, iterator2 needle_end) { size_t count = 0; while (true) { haystack_begin = std::search(haystack_begin, haystack_end, needle_begin, needle_end); if (haystack_begin == haystack_end) return count; count++; haystack_begin++; } } template <typename iterator1, typename iterator2, typename binarypredicate> size_t subsequence_count(iterator1 haystack_begin, iterator1 haystack_end, iterator2 needle_begin, iterator2 needle_end, binarypredicate predicate) { size_t count = 0; while (true) { haystack_begin = std::search(haystack_begin, haystack_end, needle_begin, needle_end, predicate); if (haystack_begin == haystack_end) return count; count++; haystack_begin++; } }
some code using this:
int main() { std::vector<int> haystack = {1, 19, 7, 23, 2, 19, 19, 19, 19}; std::vector<int> needle = {19, 19}; assert(subsequence_count(begin(haystack), end(haystack), begin(needle), end(needle) == 3); }
Comments
Post a Comment