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 assert(c.size() == 4);
27 assert(c.at(1) == "one");
28 assert(c.at(2) == "two");
29 assert(c.at(3) == "three");
30 assert(c.at(4) == "four");
31}
32
33void reserve_invariant(std::size_t n) // LWG #2156
34{
35 for (std::size_t i = 0; i < n; ++i) {
36 std::unordered_map<std::size_t, size_t> c;
37 c.reserve(n: n);
38 std::size_t buckets = c.bucket_count();
39 for (std::size_t j = 0; j < i; ++j) {
40 c[i] = i;
41 assert(buckets == c.bucket_count());
42 }
43 }
44}
45
46int main(int, char**) {
47 {
48 typedef std::unordered_map<int, std::string> C;
49 typedef std::pair<int, std::string> P;
50 P a[] = {
51 P(1, "one"),
52 P(2, "two"),
53 P(3, "three"),
54 P(4, "four"),
55 P(1, "four"),
56 P(2, "four"),
57 };
58 C c(a, a + sizeof(a) / sizeof(a[0]));
59 test(c);
60 assert(c.bucket_count() >= 5);
61 c.reserve(n: 3);
62 LIBCPP_ASSERT(c.bucket_count() == 5);
63 test(c);
64 c.max_load_factor(z: 2);
65 c.reserve(n: 3);
66 assert(c.bucket_count() >= 2);
67 test(c);
68 c.reserve(n: 31);
69 assert(c.bucket_count() >= 16);
70 test(c);
71 }
72#if TEST_STD_VER >= 11
73 {
74 typedef std::unordered_map<int,
75 std::string,
76 std::hash<int>,
77 std::equal_to<int>,
78 min_allocator<std::pair<const int, std::string>>>
79 C;
80 typedef std::pair<int, std::string> P;
81 P a[] = {
82 P(1, "one"),
83 P(2, "two"),
84 P(3, "three"),
85 P(4, "four"),
86 P(1, "four"),
87 P(2, "four"),
88 };
89 C c(a, a + sizeof(a) / sizeof(a[0]));
90 test(c);
91 assert(c.bucket_count() >= 5);
92 c.reserve(3);
93 LIBCPP_ASSERT(c.bucket_count() == 5);
94 test(c);
95 c.max_load_factor(2);
96 c.reserve(3);
97 assert(c.bucket_count() >= 2);
98 test(c);
99 c.reserve(31);
100 assert(c.bucket_count() >= 16);
101 test(c);
102 }
103#endif
104 reserve_invariant(n: 20);
105
106 return 0;
107}
108

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