this template function should complete the task
template<typename Iter> Iter nth_occurence(Iter first, Iter last, Iter first_, Iter last_, unsigned nth) { Iter it = std::search(first, last, first_, last_); if (nth == 0) return it; if (it == last) return it; return nth_occurence(it + std::distance(first_, last_), last, first_, last_, nth -1); }
using
int main() { std::string a = "hello world world world end"; std::string b = "world"; auto it1 = nth_occurence(begin(a), end(a), begin(b), end(b), 0); auto it2 = nth_occurence(begin(a), end(a), begin(b), end(b), 1); auto it3 = nth_occurence(begin(a), end(a), begin(b), end(b), 2); auto it4 = nth_occurence(begin(a), end(a), begin(b), end(b), 3); std::cout << std::distance(begin(a), it1) << "\n"; std::cout << std::distance(begin(a), it2) << "\n"; std::cout << std::distance(begin(a), it3) << "\n"; std::cout << std::boolalpha << (it4 == end(a)) << "\n"; } => 6, 12, 18, true
source share