소스 검색

to string for hash map

Kajetan Johannes Hammerle 3 년 전
부모
커밋
26090f6982
2개의 변경된 파일47개의 추가작업 그리고 2개의 파일을 삭제
  1. 30 0
      tests/HashMapTests.cpp
  2. 17 2
      utils/HashMap.h

+ 30 - 0
tests/HashMapTests.cpp

@@ -1,9 +1,11 @@
 #include "tests/HashMapTests.h"
 #include "tests/Test.h"
 #include "utils/HashMap.h"
+#include "utils/StringBuffer.h"
 
 constexpr int MAP_MIN_CAPACITY = 5;
 typedef HashMap<int, int, MAP_MIN_CAPACITY> IntMap;
+typedef StringBuffer<50> String;
 
 static void testAdd(Test& test) {
     IntMap map;
@@ -95,6 +97,31 @@ static void testEmplace(Test& test) {
     test.checkEqual(true, r5, "emplacing returns correct value 5");
 }
 
+static void testToString1(Test& test) {
+    IntMap map;
+    map.add(1, 3);
+    map.add(2, 4);
+    map.add(3, 5);
+    String s;
+    s.append(map);
+    test.checkEqual(String("[1 = 3, 2 = 4, 3 = 5]"), s, "to string 1");
+}
+
+static void testToString2(Test& test) {
+    IntMap map;
+    map.add(1, 3);
+    String s;
+    s.append(map);
+    test.checkEqual(String("[1 = 3]"), s, "to string 2");
+}
+
+static void testToString3(Test& test) {
+    IntMap map;
+    String s;
+    s.append(map);
+    test.checkEqual(String("[]"), s, "to string 3");
+}
+
 void HashMapTests::test() {
     Test test("HashMap");
     testAdd(test);
@@ -104,5 +131,8 @@ void HashMapTests::test() {
     testClear(test);
     testOverflow(test);
     testEmplace(test);
+    testToString1(test);
+    testToString2(test);
+    testToString3(test);
     test.finalize();
 }

+ 17 - 2
utils/HashMap.h

@@ -1,9 +1,8 @@
 #ifndef HASHMAP_H
 #define HASHMAP_H
 
-#include <iostream>
-
 #include "utils/Array.h"
+#include "utils/StringBuffer.h"
 
 template<typename K, typename V, int N_MIN>
 class HashMap final {
@@ -170,6 +169,22 @@ public:
         used.fill(false);
     }
 
+    template<int L>
+    void toString(StringBuffer<L>& s) const {
+        s.append("[");
+        bool c = false;
+        for(int i = 0; i < CAPACITY; i++) {
+            if(!used[i]) {
+                continue;
+            } else if(c) {
+                s.append(", ");
+            }
+            s.append(getKey(i)).append(" = ").append(getValue(i));
+            c = true;
+        }
+        s.append("]");
+    }
+
 private:
 
     template<typename H>