diff --git a/src/Collections/List.hpp b/src/Collections/List.hpp index c2a7362..d84ed4a 100644 --- a/src/Collections/List.hpp +++ b/src/Collections/List.hpp @@ -48,6 +48,16 @@ namespace Arbutils::Collections { return std::find(_vector.begin(), _vector.end(), value) != _vector.end(); } + /// Find the index of the first occurrence of a value in the list, return -1 if none is found. + /// \param value The value we want the index for. + /// \return The index of the first occurrence of the value in the list, or -1 if none is found. + inline size_t IndexOf(ValueT value) const { + auto it = std::find(_vector.begin(), _vector.end(), value); + if (it == _vector.end()) + return -1; + return std::distance(_vector.begin(), it); + } + inline void Append(ValueT value) { _vector.push_back(value); } inline void Insert(size_t index, ValueT value) { _vector.insert(index, value); } @@ -59,9 +69,7 @@ namespace Arbutils::Collections { inline void Resize(size_t size) { _vector.resize(size); } inline void Resize(size_t size, ValueT defaultValue) { _vector.resize(size, defaultValue); } - inline void Remove(size_t index){ - _vector.erase(_vector.begin() + index); - } + inline void Remove(size_t index) { _vector.erase(_vector.begin() + index); } iterator begin() { return _vector.begin(); } const_iterator begin() const { return _vector.begin(); } diff --git a/tests/ListTests.cpp b/tests/ListTests.cpp index ab2ccb2..4ea928f 100644 --- a/tests/ListTests.cpp +++ b/tests/ListTests.cpp @@ -60,6 +60,15 @@ TEST_CASE("Create list of bools, assign to it", "[Utilities]") { CHECK(ls[1]); } +TEST_CASE("Test IndexOf", "[Utilities]") { + auto ls = List({5, 200, 1500, -500, 5, 300, -500}); + CHECK(ls.IndexOf(5) == 0); + CHECK(ls.IndexOf(1500) == 2); + CHECK(ls.IndexOf(300) == 5); + CHECK(ls.IndexOf(684) == -1); +} + + #endif \ No newline at end of file