1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9// <unordered_map>
10
11// template <class Key, class T, class Hash = hash<Key>, class Pred = equal_to<Key>,
12// class Alloc = allocator<pair<const Key, T>>>
13// class unordered_map
14
15// void reserve(size_type n);
16
17#include <unordered_map>
18#include <string>
19#include <cassert>
20
21#include "test_macros.h"
22#include "min_allocator.h"
23
24template <class C>
25void test(const C& c)
26{
27 assert(c.size() == 4);
28 assert(c.at(1) == "one");
29 assert(c.at(2) == "two");
30 assert(c.at(3) == "three");
31 assert(c.at(4) == "four");
32}
33
34void reserve_invariant(std::size_t n) // LWG #2156
35{
36 for (std::size_t i = 0; i < n; ++i)
37 {
38 std::unordered_map<std::size_t, size_t> c;
39 c.reserve(n: n);
40 std::size_t buckets = c.bucket_count();
41 for (std::size_t j = 0; j < i; ++j)
42 {
43 c[i] = i;
44 assert(buckets == c.bucket_count());
45 }
46 }
47}
48
49int main(int, char**)
50{
51 {
52 typedef std::unordered_map<int, std::string> C;
53 typedef std::pair<int, std::string> P;
54 P a[] =
55 {
56 P(1, "one"),
57 P(2, "two"),
58 P(3, "three"),
59 P(4, "four"),
60 P(1, "four"),
61 P(2, "four"),
62 };
63 C c(a, a + sizeof(a)/sizeof(a[0]));
64 test(c);
65 assert(c.bucket_count() >= 5);
66 c.reserve(n: 3);
67 LIBCPP_ASSERT(c.bucket_count() == 5);
68 test(c);
69 c.max_load_factor(z: 2);
70 c.reserve(n: 3);
71 assert(c.bucket_count() >= 2);
72 test(c);
73 c.reserve(n: 31);
74 assert(c.bucket_count() >= 16);
75 test(c);
76 }
77#if TEST_STD_VER >= 11
78 {
79 typedef std::unordered_map<int, std::string, std::hash<int>, std::equal_to<int>,
80 min_allocator<std::pair<const int, std::string>>> C;
81 typedef std::pair<int, std::string> P;
82 P a[] =
83 {
84 P(1, "one"),
85 P(2, "two"),
86 P(3, "three"),
87 P(4, "four"),
88 P(1, "four"),
89 P(2, "four"),
90 };
91 C c(a, a + sizeof(a)/sizeof(a[0]));
92 test(c);
93 assert(c.bucket_count() >= 5);
94 c.reserve(3);
95 LIBCPP_ASSERT(c.bucket_count() == 5);
96 test(c);
97 c.max_load_factor(2);
98 c.reserve(3);
99 assert(c.bucket_count() >= 2);
100 test(c);
101 c.reserve(31);
102 assert(c.bucket_count() >= 16);
103 test(c);
104 }
105#endif
106 reserve_invariant(n: 20);
107
108 return 0;
109}
110

source code of libcxx/test/std/containers/unord/unord.map/reserve.pass.cpp