-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtests.cpp
2225 lines (1913 loc) · 83 KB
/
tests.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* STL HashMap Test Harness
* Created by Avery Wang (lecturer for 2019-2020 - [email protected])
*
* V1 (spring 2020) - basic, rehash, operators, special members tests
* V2 (fall 2020) - improve special members test
* V3 (winter 2021) - added iterator tests, factored out edge case and const-correctness tests
* - added benchmarking tests
*
* DO NOT SUBMIT THIS FILE (unless you added extra tests for us)
*/
#include "hashmap.h"
#include "test_settings.cpp"
using namespace std;
#include <vector>
#include <unordered_map>
#include <random>
#include <utility>
#include <algorithm>
#include <sstream>
#include <set>
#include <iomanip>
#include <chrono> // for chrono timers
// ----------------------------------------------------------------------------------------------
// Global Constants and Type Alises (DO NOT EDIT)
using clock_type = std::chrono::high_resolution_clock;
using ns = std::chrono::nanoseconds;
const std::vector<std::pair<std::string, int> > vec {
{"A", 3}, {"B", 2}, {"C", 1}, {"A", -5}, {"B", 3}, {"A", 5}, {"C", 1},
{"D", 10}, {"K", 30}, {"Avery", 2020}, {"Anna", 2020}, {"Ali", 2019}
};
const std::vector<std::string> keys {"A", "B", "C", "Not found"};
template <typename Map1, typename Map2> bool check_map_equal(Map1& map, Map2& answer) {
if (answer.empty() != map.empty() || answer.size() != map.size()) return false;
for (const auto& [key, mapped] : answer) {
if (map.contains(key) == false || map.at(key) != mapped) return false;
}
return true;
}
// Runtime assertion check
// Equivalent to CHECK_TRUE
struct VerifyTrueAssertionFailure {
int line;
};
void VERIFY_TRUE(bool condition, int line) {
if (!condition) {
throw VerifyTrueAssertionFailure{line};
}
}
// ----------------------------------------------------------------------------------------------
/* Milestone 1 Test Cases (DO NOT EDIT) */
void A_basic() {
/*
* Verifies basic operations by comparing behavior with std::unordered_map
* - default ctor
* - size, empty, bucket_count
* - contains, at (used as an r-value)
*
* Mainly checking that check_map_equal compiles correctly.
*/
std::unordered_map<std::string, int> answer;
HashMap<std::string, int> map;
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
VERIFY_TRUE(map.bucket_count() == 10, __LINE__);
}
void B_insert() {
/*
* Verifies functionality of insert.
*/
std::unordered_map<std::string, int> answer;
HashMap<std::string, int> map;
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
VERIFY_TRUE(map.bucket_count() == 10, __LINE__);
for (const auto& kv_pair : vec) {
answer.insert(kv_pair);
map.insert(kv_pair);
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
}
VERIFY_TRUE(map.bucket_count() == 10, __LINE__);
}
void C_clear() {
/*
* Tests clear operations, and ensure map is in valid
* state after a call to clear.
*/
std::unordered_map<std::string, int> answer;
HashMap<std::string, int> map;
for (size_t j = 0; j < 3; ++j) {
for (const auto& kv_pair : vec) {
answer.insert(kv_pair);
map.insert(kv_pair);
}
answer.clear();
map.clear();
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
}
}
void D_at() {
/*
* Tests whether at correctly returns a reference.
*/
std::unordered_map<std::string, int> answer;
HashMap<std::string, int> map;
answer.insert({"A", 42});
answer.insert({"B", 137});
answer.insert({"C", -1});
// at returns a reference, so assigning their return value on the left-hand value should
// change the contents of the map.
answer.at("A") = 42;
answer.at("B") = 137;
answer.at("A") = -42;
answer.at("C") = answer.at("A");
VERIFY_TRUE(answer.at("A") == -42, __LINE__);
VERIFY_TRUE(answer.at("B") == 137, __LINE__);
VERIFY_TRUE(answer.at("C") == -42, __LINE__);
// verify that we can save the reference returned by at.
auto copy = answer.at("A");
auto& ref = answer.at("B");
copy = 0;
(void)copy;
ref = 0;
VERIFY_TRUE(answer.at("A") == -42, __LINE__);
VERIFY_TRUE(answer.at("B") == 0, __LINE__);
// verify that correct exceptions are thrown
HashMap<std::string, int> map2;
bool correct_exception = false;
try {
map2.at("Exists") = 5;
} catch (const std::out_of_range& e) {
correct_exception = true;
}
VERIFY_TRUE(correct_exception, __LINE__);
map2.insert({"Exists", 4});
VERIFY_TRUE(map2.contains("Exists"), __LINE__);
VERIFY_TRUE(!map2.contains("Does not exist"), __LINE__);
correct_exception = true;
try {
map2.at("Does not exist") = 5;
} catch (const std::out_of_range& e) {
correct_exception = true;
}
VERIFY_TRUE(correct_exception, __LINE__);
}
template <typename... Ts>
void ensure_at_return_is_const(Ts...) {}
template <typename T>
auto ensure_at_return_is_const(const T& map) -> decltype((void) (map.at(0) = 3), void()) {
VERIFY_TRUE(false, __LINE__);
// If you run into an error here, this means your return value of const
// at is a non-const reference. Why is that wrong?
// Details about this error (it's a hacky sfinae technique):
// we tried running the following code segment (in the decltype line)
// const T& map;
// map.at(0) = 3;
// if the segment compiles, then this function is run (which fails)
// if the segment does not compile, the variadic template before runs (which passes)
}
void E_at_const_correct() {
std::unordered_map<std::string, int> answer;
HashMap<std::string, int> map1;
VERIFY_TRUE(check_map_equal(map1, answer), __LINE__); // both maps should be empty
for (const auto& kv_pair : vec) {
answer.insert(kv_pair);
map1.insert(kv_pair);
VERIFY_TRUE(check_map_equal(map1, answer), __LINE__); // both maps have same elements
}
// create const references to the maps
// to see if these const references work correctly
const auto& c_ref_answer = answer;
const auto& c_ref_map1 = map1;
// check if we can still check contents of maps as equal
// even when dealing with const references
VERIFY_TRUE(check_map_equal(c_ref_map1, c_ref_answer), __LINE__);
for (const auto& [key, mapped] : answer) {
VERIFY_TRUE(c_ref_map1.contains(key), __LINE__);
VERIFY_TRUE(map1.contains(key), __LINE__);
VERIFY_TRUE(c_ref_map1.at(key) == mapped, __LINE__); // confirm parameter is a const reference
VERIFY_TRUE(map1.at(key) == mapped, __LINE__);
VERIFY_TRUE(check_map_equal(map1, answer), __LINE__);
}
map1.erase("A");
answer.erase("A");
for (const auto& [key, mapped] : answer) {
VERIFY_TRUE(c_ref_map1.contains(key), __LINE__);
VERIFY_TRUE(c_ref_map1.at(key) == mapped, __LINE__); // confirm parameter is a const reference
VERIFY_TRUE(check_map_equal(map1, answer), __LINE__);
}
HashMap<int, int> map3;
map3.insert({0, 0});
ensure_at_return_is_const(map3); // confirm return value is a const reference
}
void F_custom_bucket_count() {
/*
* Tests ctor taking in num_buckets, while hash function
* still uses the default. Also tests correct function of load_factor.
*/
HashMap<int, int> many_buckets(10000);
HashMap<int, int> one_bucket(1);
std::unordered_map<int, int> answer;
for (int i = 0; i < 100; ++i) {
many_buckets.insert({i, -i});
one_bucket.insert({i, -i});
answer.insert({i, -i});
}
VERIFY_TRUE(check_map_equal(many_buckets, answer), __LINE__);
VERIFY_TRUE(check_map_equal(one_bucket, answer), __LINE__);
VERIFY_TRUE(many_buckets.bucket_count() == 10000, __LINE__);
VERIFY_TRUE(one_bucket.bucket_count() == 1, __LINE__);
float epsilon = 0.001;
VERIFY_TRUE(many_buckets.load_factor() - 0.01 < epsilon, __LINE__);
VERIFY_TRUE(one_bucket.load_factor() - 100 < epsilon, __LINE__);
}
void G_custom_hash_function() {
/*
* Tests ctor taking in a num_buckets and hash function.
* We use a hash function that distributes similar inputs
* more randomly across the buckets.
*/
using K = int;
using V = char;
auto identity_shifted = [](const K& key) {
return (key * 43037 + 52081) % 79229;
};
// hey, didn't you use this from assignment 1?
// now you know what the priority queue decltype comes from!
HashMap<K, V, decltype(identity_shifted)> map(75, identity_shifted);
std::unordered_map<K, V> answer;
for (int i = 0; i < 50; ++i) {
map.insert({i, 'a' + i});
answer.insert({i, 'a' + i});
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
}
}
void H_erase() {
/*
* Tests erase operation in combination with basic operations.
*/
std::unordered_map<std::string, int> answer;
HashMap<std::string, int> map;
for (const auto& kv_pair : vec) {
answer.insert(kv_pair);
map.insert(kv_pair);
}
// remove one and insert two back at a time
for (size_t i = 0; i < vec.size(); ++i) {
auto& [key1, mapped1] = vec[i];
auto& pair2 = vec[(i+3) % vec.size()];
answer.erase(key1);
map.erase(key1);
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
answer.erase("Not a key");
map.erase("Not a key");
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
answer.insert(pair2);
map.insert(pair2);
}
// remove one at a time, until map is empty
for (size_t i = 0; i < vec.size(); ++i) {
auto& [key1, mapped1] = vec[(i+3) % vec.size()];
answer.erase(key1);
map.erase(key1);
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
}
}
void I_rehash_basic() {
/*
* Verifies external correct after call to M1_Review.
* Note that this does not actually verify if the linked lists are correct,
* merely verifies that after call to M1_Review, all method calls are still valid,
* and bucket_count is correct.
*/
HashMap<int, int> map;
std::unordered_map<int, int> answer;
std::vector<int> vals;
VERIFY_TRUE(map.bucket_count() == 10, 28);
for (size_t M1_Review_count : {10, 20, 20, 15, 1000, 2, 1, 2, 1}) {
map.rehash(M1_Review_count);
VERIFY_TRUE(map.bucket_count() == M1_Review_count, __LINE__);
for (size_t i = 0; i < 18; ++i) {
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
map.erase(i);
answer.erase(i);
}
map.clear();
answer.clear();
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
for (size_t i = 1; i < 17; ++i) {
map.insert({i, i});
answer.insert({i, i});
}
}
try {
map.rehash(0);
VERIFY_TRUE(false, __LINE__); // you didn't throw an exception!
} catch (const std::out_of_range& e) {
// Great! You threw the correct exception.
} catch (const std::exception& e) {
VERIFY_TRUE(false, __LINE__); // you threw the wrong exception!
}
}
__attribute__((unused)) void unused_rehash_correct_by_time() {
/*
* This was previously a test when rehash was part of the assignment. However, it did not work
* well with the compiler optimizations, so we will not include this test. If a future lecturer
* wants to add rehash back into the assignment, they can experiment with this test.
*
* Here's to spending lots of time on tests that get removed from the assignment!
*
* This test tries to check if you hashed elements to the buckets correctly
* by adding a specific number of elements, and measuring the time it takes
* to call contains. The idea is that if bucket 0 is supposed to have 10 times
* the number of elements as bucket 1, calling contains on an element
* that should be hashed to bucket 0 but is not present should take 10 times
* longer that calling contains on an element that should be hashed to bucket 1
* but is not present.
*
* Obviously, this is less than perfect, since it's hard to predict how
* fast your computer is running linked list operations. There are two parameters
* below. One is called tolerance (let me know if I'm using the term incorrectly)
* which determines the amount of leeway we give for any differences from the
* expected time (0.5 means 50% leeway). The second is trials. You can try
* increasing that to see if you get better results.
*
* Play around with this and let me know if you find something interesting,
* or if you have suggestions to make this test better. There are also
* cool number theory results, as hashing is inherently an idea from
* cryptography. Ask Avery if you are curious!
*/
using K = int;
using V = int;
float tolerance = 0.5; // makes me feel like an engineer, probably using the term wrong
int trials = 1000; // increase if necessary, Central Limit Theorem!
// in case std::hash<K> is different on your compiler.
auto identity = [](const K& key) { return key; };
HashMap<K, V, decltype(identity)> map(6, identity);
// bucket(elements): 0(0), 1(100), 2(1500), 3(500), 4(1500), 5(6000)
for (int i = 1; i <= 100; ++i) map.insert({6*i+1, i}); // bucket 1
for (int i = 1; i <= 1500; ++i) map.insert({6*i+2, i}); // bucket 2
for (int i = 1; i <= 500; ++i) map.insert({6*i+3, i}); // bucket 3
for (int i = 1; i <= 1500; ++i) map.insert({6*i+4, i}); // bucket 4
for (int i = 1; i <= 6000; ++i) map.insert({6*i+5, i}); // bucket 5
std::unordered_map<int, float> bucket_times_6;
for (int i = 0; i < 6; ++i) {
auto start = clock_type::now();
for (int j = 0; j < trials; ++j) map.contains(i);
auto end = clock_type::now();
auto elapsed = std::chrono::duration_cast<ns>(end - start);
bucket_times_6.insert({i, elapsed.count()});
}
map.rehash(3);
std::unordered_map<int, float> bucket_times_3;
for (int i = 0; i < 3; ++i) {
auto start = clock_type::now();
for (int j = 0; j < trials; ++j) map.contains(i);
auto end = clock_type::now();
auto elapsed = std::chrono::duration_cast<ns>(end - start);
bucket_times_3.insert({i, elapsed.count()});
}
map.rehash(2);
std::unordered_map<int, float> bucket_times_2;
for (int i = 0; i < 2; ++i) {
auto start = clock_type::now();
for (int j = 0; j < trials; ++j) map.contains(i);
auto end = clock_type::now();
auto elapsed = std::chrono::duration_cast<ns>(end - start);
bucket_times_2.insert({i, elapsed.count()});
}
// Time to pull out the Chinese Remainder Theorem!
// take the unique bijection Z/6 -> Z/3 x Z/2
// bucket(elements) mod 6: 0(0), 1(100), 2(1500), 3(500), 4(1500), 5(6000)
// bucket(elements) mod 3: 0+3(500), 1+4(1600), 2+5(7500)
// bucket(elements) mod 2: 0+2+4(3000), 1+3+5(7500)
float ratio6_10 = float(bucket_times_6[1])/(bucket_times_6[0]+1);
float ratio6_23 = bucket_times_6[2]/bucket_times_6[3]; // expected: 1500/500
float ratio6_54 = bucket_times_6[5]/bucket_times_6[4]; // expected: 6000/1500
float ratio3_10 = bucket_times_3[1]/bucket_times_3[0]; // expected: 1600/500
float ratio3_21 = bucket_times_3[2]/bucket_times_3[1]; // expected: 7500/1600
float ratio2_10 = bucket_times_2[1]/bucket_times_2[0]; // expected: 7500/3000
// experiments are noisy, so let's give you some acceptable tolerance
VERIFY_TRUE(ratio6_10 > 10, __LINE__);
VERIFY_TRUE(ratio6_23 < (1+tolerance)*1500/500 && ratio6_23 > 1/(1+tolerance)*1500/500, __LINE__);
VERIFY_TRUE(ratio6_54 < (1+tolerance)*6000/1500 && ratio6_54 > 1/(1+tolerance)*6000/1500, __LINE__);
VERIFY_TRUE(ratio3_10 < (1+tolerance)*1600/500 && ratio3_10 > 1/(1+tolerance)*1600/500, __LINE__);
VERIFY_TRUE(ratio3_21 < (1+tolerance)*7500/1600 && ratio3_21 > 1/(1+tolerance)*7500/1600, __LINE__);
VERIFY_TRUE(ratio2_10 < (1+tolerance)*7500/3000 && ratio2_10 > 1/(1+tolerance)*7500/3000, __LINE__);
// fun fact: we had to add an -O0 flag because the compiler was optimizing our code
// a little too well. Turns out that the runtime all of these is the same with optimization (!)
}
void J_iter_foreach_one_bucket() {
/* Tests whether iterators are supported via a simple for-each loop
* Uses begin() and end() of your HashMap, in addition to
* the ctor and operators =, !=, and ++ of your iterator.
*/
std::set<std::pair<int, int> > questions {
{1, 1}, {2, 2}, {30, 30}, {140, 140}, {21, 21}
};
HashMap<int, int> map10(1); // can your iterator traverse normal use case?
for (const auto& pair : questions) {
map10.insert(pair);
}
std::set<std::pair<int, int> > answers10;
for (const auto& pair : map10) {
VERIFY_TRUE(answers10.insert(pair).second == true, __LINE__);
}
VERIFY_TRUE(questions == answers10, __LINE__);
}
void K_iter_foreach_filled_buckets() {
/* Tests whether iterators are supported via a simple for-each loop
* Uses begin() and end() of your HashMap, in addition to
* the ctor and operators =, !=, and ++ of your iterator.
*/
std::set<std::pair<int, int> > questions;
auto identity = [](auto i) {return i;};
HashMap<int, int, decltype(identity)> map10(6, identity); // can your iterator traverse normal use case?
for (int i = 0; i < 10; ++i) {
map10.insert({i, i});
questions.insert({i, i});
}
std::set<std::pair<int, int> > answers10;
for (const auto& pair : map10) VERIFY_TRUE(answers10.insert(pair).second == true, __LINE__);
VERIFY_TRUE(questions == answers10, __LINE__);
}
void L_iter_foreach_split_buckets() {
/* Tests whether iterators are supported via a simple for-each loop
* Uses begin() and end() of your HashMap, in addition to
* the ctor and operators =, !=, and ++ of your iterator.
*/
std::set<std::pair<int, int> > questions;
auto identity = [](auto i) {return i;};
HashMap<int, int, decltype(identity)> map10(6, identity); // can your iterator traverse normal use case?
for (int i = 0; i < 20; i += 2) {
map10.insert({i, i});
questions.insert({i, i});
}
std::set<std::pair<int, int> > answers10;
for (const auto& pair : map10) VERIFY_TRUE(answers10.insert(pair).second == true, __LINE__);
VERIFY_TRUE(questions == answers10, __LINE__);
}
void M_iter_foreach_edge() {
/* Tests a few edge cases for your iterator, such as checking the bounds */
std::set<std::pair<int, int> > questions {
{6, 6}, {1, 1}, {2, 2}, {3, 3}, {4, 4}
};
HashMap<int, int> map1(1); // one bucket with all the elements
HashMap<int, int> map5(5); // exactly one per bucket
HashMap<int, int> map10(100); // a lot of empty buckets
HashMap<int, int> empty; // won't add anything to this one
for (const auto& pair : questions) {
map1.insert(pair);
map5.insert(pair);
map10.insert(pair);
}
std::set<std::pair<int, int> > answers1, answers5, answers10;
for (const auto& pair : map1) VERIFY_TRUE(answers1.insert(pair).second == true, __LINE__);
for (const auto& pair : map5) VERIFY_TRUE(answers5.insert(pair).second == true, __LINE__);
for (const auto& pair : map10) VERIFY_TRUE(answers10.insert(pair).second == true, __LINE__);
for (const auto& pair __attribute__((unused)) : empty) VERIFY_TRUE(false, __LINE__); // this should not run!
VERIFY_TRUE(questions == answers1, __LINE__);
VERIFY_TRUE(questions == answers5, __LINE__);
VERIFY_TRUE(questions == answers10, __LINE__);
}
void N_iter_forward_operators() {
/* Tests the more advanced operators, that are required
* since the iterator can be a forward iterator */
std::set<std::pair<int, int> > questions {
{1, 1}, {2, 4}, {3, 9}
};
// Note to reader: yes, I spent so much time writing these awesome test cases
// and then decided to make this part optional. What a great use of my spring break.
// It's not like I have anything else to do, right?
HashMap<int, int> map; // can your iterator traverse normal use case?
for (const auto& pair : questions) {
map.insert(pair);
}
// note: we make no assumptions about which specifc element is in which order!
auto iter = map.begin(); // iter->0th element
VERIFY_TRUE((*iter).first == (*iter).second, __LINE__); // behavior of * operator
VERIFY_TRUE(iter-> first * iter->first == iter->second, __LINE__);// behavior of -> operator
VERIFY_TRUE(iter == iter, __LINE__); // behavior of == operator
VERIFY_TRUE(!(iter != iter), __LINE__); // behavior of != operator
(*iter).second = -1; // behavior of * operator as an l-value
VERIFY_TRUE((*iter).second == -1, __LINE__); // behavior of * operator as an r-value
iter->second = -2; // behavior of -> operator as an l-value
VERIFY_TRUE(iter->second == -2, __LINE__); // behavior of -> operator as an r-value
// verify correct prefix/postfix behavior (this was very tedious)
HashMap<int, int>::iterator iter0 = iter; // just to prove why type aliases are helpful
auto iter1 = ++iter; // though auto usually works as well
auto iter2 = ++iter;
auto iter3 = ++iter;
// iter0 = {1, -2}, iter1 = {2, 4}, iter3 = {3, 9}
VERIFY_TRUE(iter0->first + iter1->first + iter2->first == 6, __LINE__);
VERIFY_TRUE(iter0->first * iter1->first * iter2->first == 6, __LINE__);
VERIFY_TRUE(iter0->second + iter1->second + iter2->second == 11, __LINE__);
VERIFY_TRUE(iter0->second * iter1->second * iter2->second == -72, __LINE__);
VERIFY_TRUE(iter == map.end(), __LINE__);
iter = iter0; // iter->0
auto& iter_ref = ++iter; // iter/iter_ref->1
VERIFY_TRUE(iter_ref == iter1, __LINE__);
auto iter_ref_copy = ++iter_ref; // iter_ref_copy->2, iter/iter_ref->2
VERIFY_TRUE(iter_ref_copy == iter2, __LINE__);
VERIFY_TRUE(iter_ref == iter2, __LINE__);
auto iter_post = iter++; // iter/iter_ref->3, iter_post->2
VERIFY_TRUE(iter_post == iter2, __LINE__);
VERIFY_TRUE(iter == iter3, __LINE__);
iter_ref = map.begin(); // iter/iter_ref->0
VERIFY_TRUE(iter == iter0, __LINE__);
// Big LOL - see if you can actually trace the ++++++ operator.
auto iter_chain_pre = ++++++iter; // iter_chain_pre->3, iter/iter_ref->3
VERIFY_TRUE(iter == iter3, __LINE__);
VERIFY_TRUE(iter_chain_pre == iter3, __LINE__);
iter_ref = map.begin(); // iter/iter_ref->0
auto iter_chain_post = iter++++++; // iter/iter_ref->1, iter_chain_post->0
VERIFY_TRUE(iter == iter1, __LINE__);
VERIFY_TRUE(iter_chain_post == iter0, __LINE__);
// presumably if you pass the above ones, you probably have it working
// so I'm not gonna think about what ++iter++++ would be
}
void O_iter_algorithm_copy() {
/* Stress test of the basic operators of iterators using STL copy */
HashMap<int, int> map;
std::unordered_map<int, int> answer;
for (int i = -17; i < 10; ++i) {
map.insert({i, i*i});
}
std::copy(map.begin(), map.end(), std::inserter(answer, answer.begin()));
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
answer.clear();
const auto& c_map = map;
std::copy(c_map.begin(), c_map.end(), std::inserter(answer, answer.begin()));
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
}
void P_iter_algorithm_permutation() {
/* Stress test of the multipass functionality of forward iterators using STL is_permutation */
auto identity_shifted = [](const int& key) {
return (key * 43037 + 52081) % 79229;
};
HashMap<int, int, decltype(identity_shifted)> map1(1, identity_shifted);
HashMap<int, int> map2(3);
std::unordered_map<int, int> answer;
for (int i = -100; i < 100; ++i) {
map1.insert({i, i*i});
map2.insert({i, i*i});
answer.insert({i, i*i});
}
VERIFY_TRUE(std::is_permutation(map1.begin(), map1.end(), answer.begin(), answer.end()), __LINE__);
VERIFY_TRUE(std::is_permutation(answer.begin(), answer.end(), map1.begin(), map1.end()), __LINE__);
VERIFY_TRUE(std::is_permutation(map2.begin(), map2.end(), answer.begin(), answer.end()), __LINE__);
VERIFY_TRUE(std::is_permutation(answer.begin(), answer.end(), map2.begin(), map2.end()), __LINE__);
VERIFY_TRUE(std::is_permutation(map2.begin(), map2.end(), map1.begin(), map1.end()), __LINE__);
VERIFY_TRUE(std::is_permutation(map1.begin(), map1.end(), map2.begin(), map2.end()), __LINE__);
VERIFY_TRUE(std::is_permutation(map1.begin(), map1.end(), map1.begin(), map1.end()), __LINE__);
VERIFY_TRUE(std::is_permutation(map2.begin(), map2.end(), map2.begin(), map2.end()), __LINE__);
map1.insert({-1000, 1000});
map1.rehash(4);
map2.rehash(5);
VERIFY_TRUE(!std::is_permutation(map1.begin(), map1.end(), answer.begin(), answer.end()), __LINE__);
VERIFY_TRUE(!std::is_permutation(answer.begin(), answer.end(), map1.begin(), map1.end()), __LINE__);
VERIFY_TRUE(!std::is_permutation(map2.begin(), map2.end(), map1.begin(), map1.end()), __LINE__);
VERIFY_TRUE(!std::is_permutation(map1.begin(), map1.end(), map2.begin(), map2.end()), __LINE__);
VERIFY_TRUE(std::is_permutation(map1.begin(), map1.end(), map1.begin(), map1.end()), __LINE__);
VERIFY_TRUE(std::is_permutation(map2.begin(), map2.end(), map2.begin(), map2.end()), __LINE__);
}
void Q_iter_const_iterator() {
/* Tests the const-correct of your iterator class by asking for const_iterators via begin() and end() */
std::set<std::pair<int, int> > questions {
{1, 1}, {2, 2}, {3, 3}
};
/* testing const_iterator (iterator to const std::pair) */
HashMap<int, int> map;
for (const auto& pair : questions) map.insert(pair);
const auto& const_map = map;
std::set<std::pair<int, int> > answers;
for (const auto& pair : const_map) VERIFY_TRUE(answers.insert(pair).second == true, __LINE__);
VERIFY_TRUE(questions == answers, __LINE__);
HashMap<int, int>::const_iterator iter = const_map.begin();
VERIFY_TRUE((*iter).first == (*iter).second, __LINE__); // behavior of * operator
VERIFY_TRUE(iter->first == iter->second, __LINE__); // behavior of -> operator
VERIFY_TRUE(iter == iter, __LINE__); // behavior of == operator
VERIFY_TRUE(!(iter != iter), __LINE__); // behavior of != operator
VERIFY_TRUE(iter->second == (*iter).second, __LINE__);
auto iter1 = ++iter;
auto iter2 = ++iter;
auto iter3 = iter++;
VERIFY_TRUE(iter == const_map.end(), __LINE__);
VERIFY_TRUE(iter3 == iter2, __LINE__);
VERIFY_TRUE(iter1 != iter2, __LINE__);
/* We could have the entire operator tests here, though that feels unnecessary */
}
void R_iter_const_correct() {
/* Test the distinction between const iterator and const_iterator */
std::set<std::pair<int, int> > questions {
{1, 1}, {2, 2}, {3, 3}
};
HashMap<int, int> map;
for (const auto& pair : questions) map.insert(pair);
/* test behavior of const iterator */
HashMap<int, int>::iterator iter = map.begin();
const HashMap<int, int>::iterator c_iter = map.begin();
const HashMap<int, int>::iterator& copy = iter;
const HashMap<int, int>::iterator& copy_next = ++iter;
VERIFY_TRUE(map.begin() == c_iter, __LINE__);
VERIFY_TRUE(copy == iter, __LINE__);
VERIFY_TRUE(copy_next == iter, __LINE__);
VERIFY_TRUE(c_iter != iter, __LINE__);
// the iterator is const, but the stuff the iterator points to is not const.
(*c_iter).second = -1; // behavior of * operator as an l-value
VERIFY_TRUE((*c_iter).second == -1, __LINE__); // behavior of * operator as an r-value
c_iter->second = -2; // behavior of -> operator as an l-value
VERIFY_TRUE(c_iter->second == -2, __LINE__); // behavior of -> operator as an r-value
// these should not compile:
// *iter = {0, 0}; // *iter is a std::pair<const K, M>, since K is const, = is deleted
// ++c_iter; // ++ is non-const
VERIFY_TRUE(++++iter == map.end(), __LINE__);
/* test behavior of const const_iterator */
const auto& const_map = map;
HashMap<int, int>::const_iterator const_iter = const_map.begin();
const HashMap<int, int>::const_iterator c_const_iter_next = ++const_map.begin();
const HashMap<int, int>::const_iterator c_const_iter = const_map.begin();
// the key here is that these should compile.
++const_iter;
VERIFY_TRUE((*c_const_iter).second == -2, __LINE__);
VERIFY_TRUE(c_const_iter->second == -2, __LINE__);
VERIFY_TRUE(const_iter == c_const_iter_next, __LINE__);
VERIFY_TRUE(c_const_iter == const_map.begin(), __LINE__);
// these should not compile:
// ++c_const_iter;
// c_const_iter->second = 2;
// const_iter->second = 2;
// TODO: create SFINAE tests for testing iterator code that should not compile
}
void S_iter_const_conversion() {
/* Tests whether an iterator can implicitly convert to a const_iterator */
std::set<std::pair<int, int> > questions {
{1, 1}, {2, 2}, {3, 3}
};
HashMap<int, int> map;
const auto& cmap = map;
for (const auto& pair : questions) map.insert(pair);
HashMap<int, int>::const_iterator c_iter = cmap.begin();
HashMap<int, int>::iterator iter = map.begin();
HashMap<int, int>::const_iterator converted_iter = iter; // this results in an implicit conversion to const_iterator
VERIFY_TRUE(converted_iter == c_iter, __LINE__);
++c_iter;
++iter;
++converted_iter;
VERIFY_TRUE(static_cast<HashMap<int, int>::const_iterator>(iter) == c_iter, __LINE__);
VERIFY_TRUE(static_cast<HashMap<int, int>::const_iterator>(iter) == converted_iter, __LINE__);
++iter;
++iter;
HashMap<int, int>::const_iterator converted_end = iter;
VERIFY_TRUE(iter == map.end(), __LINE__);
VERIFY_TRUE(converted_end == cmap.end(), __LINE__);
}
void T_iter_find_member() {
/*
* Verifies functionality of the find member function, which uses the iterator class.
*/
HashMap<std::string, int> map;
for (const auto& kv_pair : vec) {
map.insert(kv_pair);
}
{
// test the non-const version of HashMap::find
auto iter_avery = map.find("Avery");
VERIFY_TRUE(iter_avery->first == "Avery", __LINE__);
VERIFY_TRUE(iter_avery->second == 2020, __LINE__);
auto iter_ali = map.find("Ali");
VERIFY_TRUE(iter_ali->first == "Ali", __LINE__);
VERIFY_TRUE(iter_ali->second == 2019, __LINE__);
iter_ali->second = 2018;
auto iter_repeat = map.find("Ali");
VERIFY_TRUE(iter_repeat->first == "Ali", __LINE__);
VERIFY_TRUE(iter_repeat->second == 2018, __LINE__);
VERIFY_TRUE(iter_ali == iter_repeat, __LINE__);
VERIFY_TRUE(iter_avery != iter_ali, __LINE__);
iter_ali->second = 2019;
auto iter_not_found = map.find("Not found");
VERIFY_TRUE(iter_not_found == map.end(), __LINE__);
}
{
// test the const version of HashMap::find
const auto& cmap = map;
auto iter_avery = cmap.find("Avery");
VERIFY_TRUE(iter_avery->first == "Avery", __LINE__);
VERIFY_TRUE(iter_avery->second == 2020, __LINE__);
auto iter_ali = cmap.find("Ali");
VERIFY_TRUE(iter_ali->first == "Ali", __LINE__);
VERIFY_TRUE(iter_ali->second == 2019, __LINE__);
auto iter_repeat = cmap.find("Ali");
VERIFY_TRUE(iter_ali == iter_repeat, __LINE__);
VERIFY_TRUE(iter_avery != iter_ali, __LINE__);
auto iter_not_found = cmap.find("Not found");
VERIFY_TRUE(iter_not_found == cmap.end(), __LINE__);
}
}
void U_iter_insert_member() {
/*
* Verifies functionality of the insert member function, returns an iterator.
* The previous test B ignores the return value.
*/
HashMap<std::string, int> map;
auto [iter_avery0, added0] = map.insert({"Avery", 3});
VERIFY_TRUE(added0, __LINE__);
VERIFY_TRUE(iter_avery0 == map.begin(), __LINE__);
VERIFY_TRUE(iter_avery0->first == "Avery", __LINE__);
VERIFY_TRUE(iter_avery0->second == 3, __LINE__);
auto [iter_avery1, added1] = map.insert({"Avery", 3});
VERIFY_TRUE(!added1, __LINE__);
VERIFY_TRUE(iter_avery0 == iter_avery1, __LINE__);
iter_avery1->second = 4;
VERIFY_TRUE(iter_avery0->second == 4, __LINE__);
auto [iter_anna2, added2] = map.insert({"Anna", 2});
VERIFY_TRUE(added2, __LINE__);
VERIFY_TRUE(iter_anna2->first == "Anna", __LINE__);
VERIFY_TRUE(iter_anna2->second == 2, __LINE__);
}
void V_iter_erase_member() {
/*
* Verifies functionality of the erase and insert. Note that this erase test takes in a parameter
* that is a const_iterator, different from test G which only takes in a key.
*/
HashMap<std::string, int> map;
map.insert({"Avery", 3});
auto iter = map.erase(map.begin());
VERIFY_TRUE(iter == map.end(), __LINE__);
auto [iter_avery0, added0] = map.insert({"Avery", 3});
VERIFY_TRUE(added0, __LINE__);
VERIFY_TRUE(iter_avery0 == map.begin(), __LINE__);
VERIFY_TRUE(iter_avery0->first == "Avery", __LINE__);
VERIFY_TRUE(iter_avery0->second == 3, __LINE__);
auto result = map.erase(iter_avery0);
VERIFY_TRUE(result == map.end(), __LINE__);
VERIFY_TRUE(map.empty(), __LINE__);
auto [iter_avery1, added1] = map.insert({"Avery", 4});
VERIFY_TRUE(added0, __LINE__);
VERIFY_TRUE(iter_avery1->second == 4, __LINE__);
auto [iter_anna2, added2] = map.insert({"Anna", 2});
VERIFY_TRUE(added2, __LINE__);
VERIFY_TRUE(iter_anna2->first == "Anna", __LINE__);
VERIFY_TRUE(iter_anna2->second == 2, __LINE__);
auto next = map.erase(iter_anna2);
VERIFY_TRUE(next == map.end() || next == iter_avery1, __LINE__);
VERIFY_TRUE(iter_avery1 == map.begin(), __LINE__);
auto next_avery = map.erase(iter_avery1);
VERIFY_TRUE(next_avery == map.end(), __LINE__);
VERIFY_TRUE(map.begin() == map.end(), __LINE__);
}
#if RUN_TEST_2A
void A_range_ctor_basic() {
/* Simple test of the range ctor taking in two iterators to another collection */
std::vector<std::pair<std::string, int>> values {
{"Ignore me", 100}, {"A", 3}, {"B", 2}, {"C", 1}, {"A", -5}, {"B", 3}, {"A", 5}, {"C", 1}
};
std::unordered_map<std::string, int> answer {values.begin()++, values.end()}; // skips the first "Ignore me" pair
HashMap<std::string, int> map {values.begin()++, values.end()};
VERIFY_TRUE(check_map_equal(map, answer), __LINE__); // maps should be equal, if not, you didn't transfer all the elements!
}
#endif
#if RUN_TEST_2B
void B_range_ctor_edge() {
/* Simple test of the range ctor taking in two iterators to another collection */
std::vector<std::pair<std::string, int>> values {
{"Ignore me", 100}
};
{
// range has exactly one element
std::unordered_map<std::string, int> answer {values.begin(), values.end()};
HashMap<std::string, int> map {values.begin(), values.end()};
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
}
{
// range has no elements (first == last) because two ends were passed in
std::unordered_map<std::string, int> answer {values.end(), values.end()};
HashMap<std::string, int> map {values.end(), values.end()};
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
}
{
// range has no elements (first == last) since the container was empty
std::vector<std::pair<std::string, int>> empty;
std::unordered_map<std::string, int> answer {empty.begin(), empty.end()};
HashMap<std::string, int> map {empty.begin(), empty.end()};
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
}
}
#endif
#if RUN_TEST_2C
void C_initializer_list_ctor_basic() {
/* Tests initializer_list via a simple example */
std::unordered_map<std::string, int> answer {
{"A", 3}, {"B", 2}, {"C", 1}, {"A", -5}, {"B", 3}, {"A", 5}, {"C", 1}
};
HashMap<std::string, int> map {
{"A", 3}, {"B", 2}, {"C", 1}, {"A", -5}, {"B", 3}, {"A", 5}, {"C", 1}
};
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
}
#endif
#if RUN_TEST_2D
void D_initializer_list_ctor_edge() {
/* Tests initializer_list via a few edge cases example */
std::unordered_map<std::string, int> answer {{"A", 3}};
HashMap<std::string, int> map {{"A", 3}};
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
std::unordered_map<std::string, int> empty_answer ({});
HashMap<std::string, int> empty ({});
VERIFY_TRUE(check_map_equal(empty, empty_answer), __LINE__);
}
#endif
#if RUN_TEST_3A
void A_index_operator() {
/*
* Tests the indexing operator to ensure it has the functionality of at(),
* and also supports auto-insertion.
*/
std::unordered_map<std::string, int> answer;
HashMap<std::string, int> map;
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
VERIFY_TRUE(answer["Autoinsert"] == map["Autoinsert"], __LINE__);
VERIFY_TRUE(answer["Autoinsert"] == int(), __LINE__);
for (const auto& [key, value] : vec) {
answer[key] = value;
map[key] = value;
VERIFY_TRUE(check_map_equal(map, answer), __LINE__);
VERIFY_TRUE(answer["Autoinsert"] == map["Autoinsert"], __LINE__);
}
}
#endif
#if RUN_TEST_3B
template <typename... Ts>
void ensure_no_const_index_op(Ts...) {}
template <typename T>
auto ensure_no_const_index_op(const T& map) -> decltype((void) (map[0]), void()) {
VERIFY_TRUE(false, __LINE__);
// The idea of this test is that there are two overloads for ensure_no_const_index_op.
// The compiler tries this current overload, which only compiles
// if map[0] compiles, but it is not supposed to
// because map a const reference and map[0] may autoinsert.
// If map[0] does not compile (as expected), then
// the varadic template overload above is called, and no runtime assertion happens.
// It's tricky to test "this code should not compile" - this is a hacky way to check that.
}
void B_index_const_correct() {
HashMap<int, int> map;
ensure_no_const_index_op(map);
// check for parameter const correct
const int key = 3;
map[key] = 6;
int r_key = 5;
map[r_key] = 2;
map[r_key] = key;
}
#endif
#if RUN_TEST_3C
void C_stream_insert_operator() {
/*
* Tries to insert the map into various streams.
* The format is described on the handout:
* {Avery:2, Anna:3}
* {}
* {Avery:2}
*/
HashMap<std::string, int> map(1);
// Test 1: print empty map
std::ostringstream oss1;
oss1 << map;
VERIFY_TRUE(oss1.str() == "{}", __LINE__);
// Test 2: print map with a single element