avltree_ut.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #include <library/cpp/testing/unittest/registar.h>
  2. #include <library/cpp/containers/intrusive_avl_tree/avltree.h>
  3. class TAvlTreeTest: public TTestBase {
  4. UNIT_TEST_SUITE(TAvlTreeTest);
  5. UNIT_TEST(TestLowerBound);
  6. UNIT_TEST(TestIterator);
  7. UNIT_TEST_SUITE_END();
  8. private:
  9. void TestLowerBound();
  10. void TestIterator();
  11. class TIt;
  12. struct TItCompare {
  13. static inline bool Compare(const TIt& l, const TIt& r) noexcept;
  14. };
  15. class TIt: public TAvlTreeItem<TIt, TItCompare> {
  16. public:
  17. TIt(int val = 0)
  18. : Val(val)
  19. {
  20. }
  21. int Val;
  22. };
  23. using TIts = TAvlTree<TIt, TItCompare>;
  24. };
  25. inline bool TAvlTreeTest::TItCompare::Compare(const TIt& l, const TIt& r) noexcept {
  26. return l.Val < r.Val;
  27. }
  28. UNIT_TEST_SUITE_REGISTRATION(TAvlTreeTest);
  29. void TAvlTreeTest::TestLowerBound() {
  30. TIts its;
  31. TIt it1(5);
  32. TIt it2(2);
  33. TIt it3(10);
  34. TIt it4(879);
  35. TIt it5(1);
  36. TIt it6(52);
  37. TIt it7(4);
  38. TIt it8(5);
  39. its.Insert(&it1);
  40. its.Insert(&it2);
  41. its.Insert(&it3);
  42. its.Insert(&it4);
  43. its.Insert(&it5);
  44. its.Insert(&it6);
  45. its.Insert(&it7);
  46. its.Insert(&it8);
  47. TIt it_zero(0);
  48. TIt it_large(1000);
  49. UNIT_ASSERT_EQUAL(its.LowerBound(&it3), &it3);
  50. UNIT_ASSERT_EQUAL(its.LowerBound(&it_zero), &it5);
  51. UNIT_ASSERT_EQUAL(its.LowerBound(&it_large), nullptr);
  52. }
  53. void TAvlTreeTest::TestIterator() {
  54. TIts its;
  55. TIt it1(1);
  56. TIt it2(2);
  57. TIt it3(3);
  58. TIt it4(4);
  59. TIt it5(5);
  60. TIt it6(6);
  61. TIt it7(7);
  62. its.Insert(&it3);
  63. its.Insert(&it1);
  64. its.Insert(&it7);
  65. its.Insert(&it5);
  66. its.Insert(&it4);
  67. its.Insert(&it6);
  68. its.Insert(&it2);
  69. TVector<int> res;
  70. for (const TIt& i : its) {
  71. res.push_back(i.Val);
  72. }
  73. TVector<int> expected{1, 2, 3, 4, 5, 6, 7};
  74. UNIT_ASSERT_EQUAL(res, expected);
  75. res.clear();
  76. for (TIt& i : its) {
  77. res.push_back(i.Val);
  78. }
  79. UNIT_ASSERT_EQUAL(res, expected);
  80. res.clear();
  81. const TIts* constIts = &its;
  82. for (TIts::const_iterator i = constIts->begin(); i != constIts->end(); ++i) {
  83. res.push_back(i->Val);
  84. }
  85. UNIT_ASSERT_EQUAL(res, expected);
  86. }