From 380a53f02f3f5fd4037e6b743a0ca8fadfe754ca Mon Sep 17 00:00:00 2001 From: Haoyu Qiu Date: Sat, 7 May 2022 20:16:11 +0800 Subject: Add search methods for packed arrays * count() * find() * rfind() --- core/templates/cowdata.h | 32 ++++++++++++++++++++++++++++++++ core/templates/vector.h | 2 ++ 2 files changed, 34 insertions(+) (limited to 'core/templates') diff --git a/core/templates/cowdata.h b/core/templates/cowdata.h index f1ac32928f..e760fc2176 100644 --- a/core/templates/cowdata.h +++ b/core/templates/cowdata.h @@ -183,6 +183,8 @@ public: } int find(const T &p_val, int p_from = 0) const; + int rfind(const T &p_val, int p_from = -1) const; + int count(const T &p_val) const; _FORCE_INLINE_ CowData() {} _FORCE_INLINE_ ~CowData(); @@ -349,6 +351,36 @@ int CowData::find(const T &p_val, int p_from) const { return ret; } +template +int CowData::rfind(const T &p_val, int p_from) const { + const int s = size(); + + if (p_from < 0) { + p_from = s + p_from; + } + if (p_from < 0 || p_from >= s) { + p_from = s - 1; + } + + for (int i = p_from; i >= 0; i--) { + if (get(i) == p_val) { + return i; + } + } + return -1; +} + +template +int CowData::count(const T &p_val) const { + int amount = 0; + for (int i = 0; i < size(); i++) { + if (get(i) == p_val) { + amount++; + } + } + return amount; +} + template void CowData::_ref(const CowData *p_from) { _ref(*p_from); diff --git a/core/templates/vector.h b/core/templates/vector.h index d87e76139b..2ac7c7630a 100644 --- a/core/templates/vector.h +++ b/core/templates/vector.h @@ -92,6 +92,8 @@ public: _FORCE_INLINE_ const T &operator[](int p_index) const { return _cowdata.get(p_index); } Error insert(int p_pos, T p_val) { return _cowdata.insert(p_pos, p_val); } int find(const T &p_val, int p_from = 0) const { return _cowdata.find(p_val, p_from); } + int rfind(const T &p_val, int p_from = -1) const { return _cowdata.rfind(p_val, p_from); } + int count(const T &p_val) const { return _cowdata.count(p_val); } void append_array(Vector p_other); -- cgit v1.2.3