algorithm_tests.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #include <catch.hpp>
  8. #include "base/index_based_iterator.h"
  9. TEST_CASE("index_based_iterator tests", "[base::algorithm]") {
  10. auto v = std::vector<int>();
  11. v.insert(v.end(), { 1, 2, 3, 4, 5, 4, 3, 2, 1 });
  12. auto push_back_safe_remove_if = [](auto &v, auto predicate) {
  13. auto begin = base::index_based_begin(v);
  14. auto end = base::index_based_end(v);
  15. auto from = std::remove_if(begin, end, predicate);
  16. if (from != end) {
  17. auto newEnd = base::index_based_end(v);
  18. if (newEnd != end) {
  19. REQUIRE(newEnd > end);
  20. while (end != newEnd) {
  21. *from++ = *end++;
  22. }
  23. }
  24. v.erase(from.base(), newEnd.base());
  25. }
  26. };
  27. SECTION("allows to push_back from predicate") {
  28. push_back_safe_remove_if(v, [&v](int value) {
  29. v.push_back(value);
  30. return (value % 2) == 1;
  31. });
  32. auto expected = std::vector<int> { 2, 4, 4, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1 };
  33. REQUIRE(v == expected);
  34. }
  35. SECTION("allows to push_back while removing all") {
  36. push_back_safe_remove_if(v, [&v](int value) {
  37. if (value == 5) {
  38. v.push_back(value);
  39. }
  40. return true;
  41. });
  42. auto expected = std::vector<int> { 5 };
  43. REQUIRE(v == expected);
  44. }
  45. }