[gjs] utils: Add inline function to remove from unsorted vectors
- From: Philip Chimento <pchimento src gnome org>
- To: commits-list gnome org
- Cc:
- Subject: [gjs] utils: Add inline function to remove from unsorted vectors
- Date: Thu, 20 May 2021 05:18:24 +0000 (UTC)
commit 5ca326a66cc6cfb7b1fdcfbf0f4a1da66f63e8fa
Author: Marco Trevisan (TreviƱo) <mail 3v1n0 net>
Date: Sun May 16 17:27:05 2021 +0200
utils: Add inline function to remove from unsorted vectors
Erasing a value from a vector can be very verbose in C++, mostly if we
want to use some optimized path.
So add a generic function to handle it for the case of unsorted vectors
(the ones we care mostly in gjs).
gi/utils-inl.h | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)
---
diff --git a/gi/utils-inl.h b/gi/utils-inl.h
index bcd85876..a8155bcd 100644
--- a/gi/utils-inl.h
+++ b/gi/utils-inl.h
@@ -7,6 +7,8 @@
#include <stdint.h>
#include <type_traits> // IWYU pragma: keep
+#include <utility>
+#include <vector>
template <typename T>
constexpr void* gjs_int_to_pointer(T v) {
@@ -37,3 +39,23 @@ template <>
inline bool gjs_pointer_to_int<bool>(void* p) {
return !!gjs_pointer_to_int<int8_t>(p);
}
+
+namespace Gjs {
+
+template <typename T>
+inline bool remove_one_from_unsorted_vector(std::vector<T>* v, const T& value) {
+ // This assumes that there's only a copy of the same value in the vector
+ // so this needs to be ensured when populating it.
+ // We use the swap and pop idiom to avoid moving all the values.
+ auto it = std::find(v->begin(), v->end(), value);
+ if (it != v->end()) {
+ std::swap(*it, v->back());
+ v->pop_back();
+ g_assert(std::find(v->begin(), v->end(), value) == v->end());
+ return true;
+ }
+
+ return false;
+}
+
+} // namespace Gjs
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]