fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <algorithm>
  4. using namespace std::literals::string_literals;
  5.  
  6. template <class StringType, class Predicate, class SizeType = typename StringType::size_type>
  7. SizeType search(const StringType& where, Predicate pred, SizeType pos, SizeType n)
  8. {
  9. if (n > 0 && pos < where.size())
  10. {
  11. auto start = where.c_str(),
  12. ptr = start + pos,
  13. stop = ptr + std::min(where.size() - pos, n);
  14. do
  15. {
  16. if (pred(ptr, stop - ptr))
  17. return ptr - start;
  18. }
  19. while (++ptr < stop);
  20. }
  21. return StringType::npos;
  22. }
  23.  
  24. template <class StringType, class Predicate, class SizeType = typename StringType::size_type>
  25. SizeType search(const StringType& where, Predicate pred, SizeType pos = 0)
  26. {
  27. return search(where, pred, pos, where.size()-pos);
  28. }
  29.  
  30. int main()
  31. {
  32. std::cout << search("Hello world"s,
  33. [](auto&& str, auto n) {
  34. return n > 3 &&
  35. str[0] == 'l' &&
  36. str[1] == 'l';
  37. }
  38. ) << std::endl;
  39.  
  40. std::cout << search(L"Hello world"s,
  41. [](auto&& str, auto n) {
  42. return n > 3 &&
  43. str[0] == L'l' &&
  44. str[1] == L'l';
  45. }
  46. ) << std::endl;
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0.01s 5536KB
stdin
Standard input is empty
stdout
2
2