Skip to content

Commit

Permalink
add emplace(), add more forms for insert(), update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
rekola committed Feb 7, 2024
1 parent 992ed4d commit 2d2c1b2
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
20 changes: 18 additions & 2 deletions include/radix_cpp.h
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,10 @@ namespace radix_cpp {
return end();
}

std::pair<iterator,bool> insert(const value_type& vt) {
template <typename... Args>
std::pair<iterator,bool> emplace(Args&&... args) {
value_type vt{std::forward<Args>(args)...};

if (!data_) {
init(bucket_count);
} else if (10 * num_entries_ / data_size_ >= max_load_factor) { // Check the load factor
Expand Down Expand Up @@ -594,7 +597,7 @@ namespace radix_cpp {
bool is_new = true;
if (!node.flags) {
if (is_final) {
new (static_cast<void*>(&(node.data))) value_type(vt);
new (static_cast<void*>(&(node.data))) value_type(std::move(vt));
new (static_cast<void*>(&(node.prefix_key))) key_type(prefix_key);
} else {
new (static_cast<void*>(&(node.data))) value_type(mk_value_from_key(key));
Expand Down Expand Up @@ -625,6 +628,19 @@ namespace radix_cpp {
return std::make_pair(end(), false);
}

std::pair<iterator, bool> insert(const value_type& keyval) {
return emplace(keyval);
}

std::pair<iterator, bool> insert(value_type&& keyval) {
return emplace(std::move(keyval));
}

iterator insert(const_iterator hint, const value_type& keyval) {
(void)hint;
return emplace(keyval).first;
}

template <typename Q = mapped_type>
typename std::enable_if<!std::is_void<Q>::value, Q&>::type operator[](const key_type& key) {
auto it = find(key);
Expand Down
29 changes: 29 additions & 0 deletions tests/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,32 @@ TEST_CASE( "insert doesn't overwrite", "[insert_no_overwrite]" ) {
REQUIRE(inserted3 == false);
REQUIRE(M.size() == 2);
}

TEST_CASE( "insert with move semantics", "[insert_move]") {
radix_cpp::set<std::string> S;
std::string s = "This string is very long!!!!!!!!!!";
S.insert(std::move(s));
REQUIRE(s.empty());
REQUIRE(S.size() == 1);
auto it = S.begin();
REQUIRE(*it++ == "This string is very long!!!!!!!!!!");
REQUIRE(it == S.end());
}

TEST_CASE( "emplace with set", "[emplace_set]") {
radix_cpp::set<std::string> S;
S.emplace("a string");
S.emplace("another string");
auto it = S.begin();
REQUIRE(*it++ == "a string");
REQUIRE(*it++ == "another string");
REQUIRE(it == S.end());
}

TEST_CASE( "emplace with map", "[emplace_map]") {
radix_cpp::map<std::string, bool> S;
S.emplace("a string", true);
S.emplace("another string", true);
REQUIRE(S["a string"] == true);
REQUIRE(S["another string"] == true);
}

0 comments on commit 2d2c1b2

Please sign in to comment.