mirror of
https://github.com/RGBCube/serenity
synced 2025-07-26 10:57:34 +00:00
AK: Add HashMap(std::initializer_list<Entry>) constructor
This allows us to construct a HashMap from an initializer list like so: HashMap<K, V> hash_map = { { K, V }, { K, V } { K, V } };
This commit is contained in:
parent
1dbd264239
commit
1ed72cc580
2 changed files with 31 additions and 1 deletions
21
AK/HashMap.h
21
AK/HashMap.h
|
@ -31,6 +31,13 @@
|
||||||
#include <AK/StdLibExtras.h>
|
#include <AK/StdLibExtras.h>
|
||||||
#include <AK/Vector.h>
|
#include <AK/Vector.h>
|
||||||
|
|
||||||
|
// NOTE: We can't include <initializer_list> during the toolchain bootstrap,
|
||||||
|
// since it's part of libstdc++, and libstdc++ depends on LibC.
|
||||||
|
// For this reason, we don't support HashMap(initializer_list) in LibC.
|
||||||
|
#ifndef SERENITY_LIBC_BUILD
|
||||||
|
# include <initializer_list>
|
||||||
|
#endif
|
||||||
|
|
||||||
namespace AK {
|
namespace AK {
|
||||||
|
|
||||||
template<typename K, typename V, typename KeyTraits>
|
template<typename K, typename V, typename KeyTraits>
|
||||||
|
@ -49,7 +56,19 @@ private:
|
||||||
public:
|
public:
|
||||||
HashMap() { }
|
HashMap() { }
|
||||||
|
|
||||||
bool is_empty() const { return m_table.is_empty(); }
|
#ifndef SERENITY_LIBC_BUILD
|
||||||
|
HashMap(std::initializer_list<Entry> list)
|
||||||
|
{
|
||||||
|
ensure_capacity(list.size());
|
||||||
|
for (auto& item : list)
|
||||||
|
set(item.key, item.value);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
bool is_empty() const
|
||||||
|
{
|
||||||
|
return m_table.is_empty();
|
||||||
|
}
|
||||||
size_t size() const { return m_table.size(); }
|
size_t size() const { return m_table.size(); }
|
||||||
size_t capacity() const { return m_table.capacity(); }
|
size_t capacity() const { return m_table.capacity(); }
|
||||||
void clear() { m_table.clear(); }
|
void clear() { m_table.clear(); }
|
||||||
|
|
|
@ -36,6 +36,17 @@ TEST_CASE(construct)
|
||||||
EXPECT_EQ(IntIntMap().size(), 0u);
|
EXPECT_EQ(IntIntMap().size(), 0u);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST_CASE(construct_from_initializer_list)
|
||||||
|
{
|
||||||
|
HashMap<int, String> number_to_string {
|
||||||
|
{ 1, "One" },
|
||||||
|
{ 2, "Two" },
|
||||||
|
{ 3, "Three" },
|
||||||
|
};
|
||||||
|
EXPECT_EQ(number_to_string.is_empty(), false);
|
||||||
|
EXPECT_EQ(number_to_string.size(), 3u);
|
||||||
|
}
|
||||||
|
|
||||||
TEST_CASE(populate)
|
TEST_CASE(populate)
|
||||||
{
|
{
|
||||||
HashMap<int, String> number_to_string;
|
HashMap<int, String> number_to_string;
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue