Przeglądaj źródła

dense_set: added count

Michele Caini 3 lat temu
rodzic
commit
6f807d6f9e

+ 21 - 0
src/entt/container/dense_set.hpp

@@ -602,6 +602,27 @@ public:
         swap(threshold, other.threshold);
     }
 
+    /**
+     * @brief Returns the number of elements matching a key (either 1 or 0).
+     * @param key Key value of an element to search for.
+     * @return Number of elements matching the key (either 1 or 0).
+     */
+    [[nodiscard]] size_type count(const key_type &key) const {
+        return find(key) != end();
+    }
+
+    /**
+     * @brief Returns the number of elements matching a key (either 1 or 0).
+     * @tparam Other Type of the key value of an element to search for.
+     * @param key Key value of an element to search for.
+     * @return Number of elements matching the key (either 1 or 0).
+     */
+    template<typename Other>
+    [[nodiscard]] std::enable_if_t<is_transparent_v<hasher> && is_transparent_v<key_equal>, std::conditional_t<false, Other, size_type>>
+    count(const Other &key) const {
+        return find(key) != end();
+    }
+
     /**
      * @brief Finds an element with a given value.
      * @param value Value of an element to search for.

+ 11 - 6
test/entt/container/dense_set.cpp

@@ -24,7 +24,7 @@ struct transparent_equal_to {
 };
 
 TEST(DenseSet, Functionalities) {
-    entt::dense_set<std::size_t, entt::identity, transparent_equal_to> set;
+    entt::dense_set<int, entt::identity, transparent_equal_to> set;
 
     ASSERT_NO_THROW([[maybe_unused]] auto alloc = set.get_allocator());
 
@@ -32,7 +32,7 @@ TEST(DenseSet, Functionalities) {
     ASSERT_EQ(set.size(), 0u);
     ASSERT_EQ(set.load_factor(), 0.f);
     ASSERT_EQ(set.max_load_factor(), .875f);
-    ASSERT_EQ(set.max_size(), (std::vector<std::pair<std::size_t, std::size_t>>{}.max_size()));
+    ASSERT_EQ(set.max_size(), (std::vector<std::pair<std::size_t, int>>{}.max_size()));
 
     set.max_load_factor(.9f);
 
@@ -66,7 +66,12 @@ TEST(DenseSet, Functionalities) {
     ASSERT_EQ(set.hash_function()(42), 42);
     ASSERT_TRUE(set.key_eq()(42, 42));
 
-    set.emplace(0u);
+    set.emplace(0);
+
+    ASSERT_EQ(set.count(0), 1u);
+    ASSERT_EQ(set.count(4.2), 0u);
+    ASSERT_EQ(std::as_const(set).count(0.0), 1u);
+    ASSERT_EQ(std::as_const(set).count(42), 0u);
 
     ASSERT_FALSE(set.empty());
     ASSERT_EQ(set.size(), 1u);
@@ -75,8 +80,8 @@ TEST(DenseSet, Functionalities) {
     ASSERT_NE(std::as_const(set).begin(), std::as_const(set).end());
     ASSERT_NE(set.cbegin(), set.cend());
 
-    ASSERT_TRUE(set.contains(0u));
-    ASSERT_EQ(set.bucket(0u), 0u);
+    ASSERT_TRUE(set.contains(0));
+    ASSERT_EQ(set.bucket(0), 0u);
 
     set.clear();
 
@@ -87,7 +92,7 @@ TEST(DenseSet, Functionalities) {
     ASSERT_EQ(std::as_const(set).begin(), std::as_const(set).end());
     ASSERT_EQ(set.cbegin(), set.cend());
 
-    ASSERT_FALSE(set.contains(0u));
+    ASSERT_FALSE(set.contains(0));
 }
 
 TEST(DenseSet, Constructors) {