in.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*=============================================================================
  2. Copyright (c) 2017 Paul Fultz II
  3. in.cpp
  4. Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. ==============================================================================*/
  7. /*=============================================================================
  8. Copyright (c) 2016 Paul Fultz II
  9. in.cpp
  10. Distributed under the Boost Software License, Version 1.0. (See accompanying
  11. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  12. ==============================================================================*/
  13. #include "example.h"
  14. using namespace boost::hof;
  15. #ifdef _MSC_VER
  16. template<class R, class T>
  17. auto member_find(const R& r, const T& x) BOOST_HOF_RETURNS(r.find(x));
  18. #endif
  19. // Function to find an iterator using a containers built-in find if available
  20. BOOST_HOF_STATIC_LAMBDA_FUNCTION(find_iterator) = first_of(
  21. [](const std::string& s, const auto& x)
  22. {
  23. auto index = s.find(x);
  24. if (index == std::string::npos) return s.end();
  25. else return s.begin() + index;
  26. },
  27. #ifdef _MSC_VER
  28. // On MSVC, trailing decltype doesn't work with generic lambdas, so a
  29. // seperate function can be used instead.
  30. BOOST_HOF_LIFT(member_find),
  31. #else
  32. [](const auto& r, const auto& x) BOOST_HOF_RETURNS(r.find(x)),
  33. #endif
  34. [](const auto& r, const auto& x)
  35. {
  36. using std::begin;
  37. using std::end;
  38. return std::find(begin(r), end(r), x);
  39. }
  40. );
  41. // Implement an infix `in` operator to check if a range contains an element
  42. BOOST_HOF_STATIC_LAMBDA_FUNCTION(in) = infix(
  43. [](const auto& x, const auto& r)
  44. {
  45. using std::end;
  46. return find_iterator(r, x) != end(r);
  47. }
  48. );
  49. // Negate version of `in`
  50. BOOST_HOF_STATIC_LAMBDA_FUNCTION(not_in) = infix(compose(not _, in));
  51. int main()
  52. {
  53. // Check if vector contains element
  54. std::vector<int> numbers = { 1, 2, 3, 4, 5 };
  55. if (5 <in> numbers) std::cout << "Yes" << std::endl;
  56. // Check if string contains element
  57. std::string s = "hello world";
  58. if ("hello" <in> s) std::cout << "Yes" << std::endl;
  59. // Check if map contains element
  60. std::map<int, std::string> number_map = {
  61. { 1, "1" },
  62. { 2, "2" },
  63. { 3, "3" },
  64. { 4, "4" }
  65. };
  66. if (4 <in> number_map) std::cout << "Yes" << std::endl;
  67. // Check if map doesn't contains element
  68. if (not (8 <in> numbers)) std::cout << "No" << std::endl;
  69. if (8 <not_in> numbers) std::cout << "No" << std::endl;
  70. }