From 1d213b8b98cff227b11c67472205de2cd998e424 Mon Sep 17 00:00:00 2001 From: complexlogic <95071366+complexlogic@users.noreply.github.com> Date: Wed, 18 Oct 2023 05:54:22 +0000 Subject: [PATCH] List: Add Sort Functions (#1160) --- taglib/toolkit/tlist.h | 13 +++++++++++++ taglib/toolkit/tlist.tcc | 15 +++++++++++++++ tests/test_list.cpp | 24 ++++++++++++++++++++++++ 3 files changed, 52 insertions(+) diff --git a/taglib/toolkit/tlist.h b/taglib/toolkit/tlist.h index d7a9ed25..6171ffdb 100644 --- a/taglib/toolkit/tlist.h +++ b/taglib/toolkit/tlist.h @@ -276,6 +276,19 @@ namespace TagLib { */ bool operator!=(const List &l) const; + /*! + * Sorts this list in ascending order using operator< of T. + */ + void sort(); + + /*! + * Sorts this list in ascending order using the comparison + * function object \a comp which returns true if the first argument is + * less than the second. + */ + template + void sort(Compare&& comp); + protected: /* * If this List is being shared via implicit sharing, do a deep copy of the diff --git a/taglib/toolkit/tlist.tcc b/taglib/toolkit/tlist.tcc index 9eac8200..97da8267 100644 --- a/taglib/toolkit/tlist.tcc +++ b/taglib/toolkit/tlist.tcc @@ -330,6 +330,21 @@ bool List::operator!=(const List &l) const return d->list != l.d->list; } +template +void List::sort() +{ + detach(); + d->list.sort(); +} + +template +template +void List::sort(Compare&& comp) +{ + detach(); + d->list.sort(std::forward(comp)); +} + //////////////////////////////////////////////////////////////////////////////// // protected members //////////////////////////////////////////////////////////////////////////////// diff --git a/tests/test_list.cpp b/tests/test_list.cpp index fd9f5aae..6d954e97 100644 --- a/tests/test_list.cpp +++ b/tests/test_list.cpp @@ -35,6 +35,7 @@ class TestList : public CppUnit::TestFixture CPPUNIT_TEST(testAppend); CPPUNIT_TEST(testDetach); CPPUNIT_TEST(bracedInit); + CPPUNIT_TEST(testSort); CPPUNIT_TEST_SUITE_END(); public: @@ -122,6 +123,29 @@ public: CPPUNIT_ASSERT_EQUAL(6, *l4[2]); } + void testSort() + { + List list1 { + 3, + 2, + 1 + }; + list1.sort(); + CPPUNIT_ASSERT_EQUAL(list1[0], 1); + CPPUNIT_ASSERT_EQUAL(list1[1], 2); + CPPUNIT_ASSERT_EQUAL(list1[2], 3); + + List list2 { + 1, + 2, + 3 + }; + list2.sort([](const auto &a, const auto &b) { return a > b; }); + CPPUNIT_ASSERT_EQUAL(list2[0], 3); + CPPUNIT_ASSERT_EQUAL(list2[1], 2); + CPPUNIT_ASSERT_EQUAL(list2[2], 1); + } + }; CPPUNIT_TEST_SUITE_REGISTRATION(TestList);