From 36fc7c427c0e97478c73aed2a1461c3a8da37c66 Mon Sep 17 00:00:00 2001 From: Stuart <41457780+smp242@users.noreply.github.com> Date: Sat, 29 Nov 2025 21:19:39 -0500 Subject: [PATCH 1/3] [Term Entry] C++ Unordered-sets: insert() (#8023) - Adds new term entry for unordered_set::insert() - Includes syntax, parameters, return value, and two examples - Adds interactive Codebyte (word filter) and brief note on hash tables & collisions - Adds short rvalue/move-semantics blurb and FAQ - Path: content/cpp/concepts/unordered-set/terms/insert/unordered_set_insert.md --- .../terms/insert/unordered_set_insert.md | 208 ++++++++++++++++++ 1 file changed, 208 insertions(+) create mode 100644 content/cpp/concepts/unordered-set/terms/insert/unordered_set_insert.md diff --git a/content/cpp/concepts/unordered-set/terms/insert/unordered_set_insert.md b/content/cpp/concepts/unordered-set/terms/insert/unordered_set_insert.md new file mode 100644 index 00000000000..0459ab43722 --- /dev/null +++ b/content/cpp/concepts/unordered-set/terms/insert/unordered_set_insert.md @@ -0,0 +1,208 @@ +--- +Title: insert() +Description: Inserts element(s) into an unordered_set if they do not already exist. +Subjects: + - Code Foundations + - Computer Science +tags: + - Data Structures + - Methods + - Sets +CatalogContent: + - learn-c-plus-plus + - paths/computer-science +--- + +The **`insert()`** member function of C++’s `std::unordered_set` attempts to insert one or more new elements into the container **only if** an equivalent element does not already exist. `unordered_set` stores unique elements and uses a **hash table** for fast lookups, insertions, and deletions. + +Internally, each element’s key is transformed by a **hash function** into a bucket index. When multiple elements hash to the same bucket — known as a **hash collision** — they are grouped together within that bucket. Although average insertion and lookup are constant time (`O(1)`), heavy collisions can cause performance to degrade to linear time (`O(n)`). + +## Syntax + +```cpp +// Single element insertion (copy) +std::pair insert(const value_type& value); + +// Single element insertion (move) +std::pair insert(value_type&& value); + +// Hint insertion (ignored for unordered containers) +iterator insert(const_iterator hint, const value_type& value); + +// Range insertion +void insert(InputIterator first, InputIterator last); + +// Initializer list insertion +void insert(std::initializer_list ilist); + +// Node handle insertion (C++17) +insert_return_type insert(node_type&& nh); +iterator insert(const_iterator hint, node_type&& nh); +``` + +**Parameters** + +| Parameter | Description | +| ------------- | ---------------------------------------------------------------------- | +| `value` | The element to be inserted. | +| `hint` | Iterator hint suggesting where to insert the element (may be ignored). | +| `first, last` | Input iterators defining a range of elements to insert. | +| `ilist` | Initializer list of elements to insert. | +| `nh` | Node handle extracted from another unordered container. | + +**Return Value** + +- Returns a `std::pair`: + + - `iterator`: Points to the inserted element, or to the existing element if no insertion occurred. + - `bool`: `true` if insertion took place, `false` if the element already existed. + +For range and initializer list overloads, the return type is `void`. + +**Note: Move Semantics** + +When calling `insert()`` with std::move(obj), the function may take advantage of move semantics to transfer resources from obj instead of copying them. This uses the rvalue reference overload `value_type&& value` which can improve performance when inserting large objects, because it reuses existing resources (like memory buffers) rather than duplicating them. However, if the insertion fails because the element already exists, the state of the moved-from object (obj) is valid but unspecified — it may be empty or altered. + +## Example 1: Basic `insert()` Usage - Library Book Catalog + +```cpp +#include +#include +#include + +int main() { + std::unordered_set catalog; + + auto result1 = catalog.insert("The Hobbit"); + auto result2 = catalog.insert("1984"); + auto result3 = catalog.insert("The Hobbit"); // duplicate + + if (result1.second) + std::cout << "Added: " << *result1.first << std::endl; + if (result2.second) + std::cout << "Added: " << *result2.first << std::endl; + + if (!result3.second) + std::cout << "Duplicate found: " << *result3.first << std::endl; + + std::cout << "\nBooks in catalog:\n"; + for (const auto& title : catalog) + std::cout << "- " << title << std::endl; + + return 0; +} +``` + +**Output:** + +```shell +Added: The Hobbit +Added: 1984 +Duplicate found: The Hobbit + +Books in catalog: +- 1984 +- The Hobbit +``` + +This example models a simple library catalog where each title must be unique. `unordered_set::insert()` prevents duplicate titles from being added, demonstrating how the container automatically enforces uniqueness while allowing constant-time average insertion. + +## Example 2: Managing Unique Usernames + +```cpp +#include +#include +#include + +int main() { + std::unordered_set usernames = {"char_bean", "bilbo_baggins", "webly_45"}; + + // Attempt to insert new usernames + auto addUser = [&](const std::string& user) { + auto result = usernames.insert(user); + if (result.second) + std::cout << "Username '" << user << "' added successfully.\n"; + else + std::cout << "Username '" << user << "' already exists.\n"; + }; + + addUser("mighty_meat"); + addUser("i_love_tacos"); + addUser("char_bean"); // duplicate + addUser("tamellamas"); + + std::cout << "\nCurrent registered users:\n"; + for (const auto& name : usernames) { + std::cout << "- " << name << "\n"; + } + + return 0; +} +``` + +**Output:** + +```shell +Username 'mighty_meat' added successfully. +Username 'i_love_tacos' added successfully. +Username 'char_bean' already exists. +Username 'tamellamas' added successfully. + +Current registered users: +- tamellamas +- webly_45 +- i_love_tacos +- char_bean +- mighty_meat +- bilbo_baggins +``` + +This example models a login system where usernames must remain unique. The `insert()` method ensures that duplicates are automatically rejected. + +## Codebyte Example: Word Filter with `insert()` + +```codebyte/cpp +#include +#include +#include + +int main() { + std::unordered_set words; + std::string input; + + std::cout << "Enter words (type 'done' to finish):\n"; + + while (true) { + std::cin >> input; + if (input == "done") break; + + auto result = words.insert(input); + if (result.second) + std::cout << "'" << input << "' added.\n"; + else + std::cout << "'" << input << "' already exists!\n"; + } + + std::cout << "\nUnique words entered (" << words.size() << "):\n"; + for (const auto& word : words) + std::cout << "- " << word << "\n"; + + return 0; +} +``` + +This example acts as a word collector that keeps only unique entries. Each attempt to insert a duplicate word is automatically rejected by the `unordered_set`. + +## FAQ + +**Q: How does `insert()` differ from `emplace()`?** +`insert()` inserts an existing object, while `emplace()` constructs it directly in-place using provided arguments—often more efficient. + +**Q: What happens if I insert a duplicate element?** +The operation fails, and the returned `bool` in the result pair is `false`. + +**Q: Can `insert()` invalidate iterators?** +Only if a rehash occurs when inserting (for example, after exceeding the load factor threshold). + +**Q: What’s the time complexity of `insert()`?** +Average: **O(1)**; Worst case: **O(n)** when hash collisions occur. \ No newline at end of file From b03478582aaef333a35cada39c88fa1da64fa948 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 3 Dec 2025 18:12:48 +0530 Subject: [PATCH 2/3] Rename unordered_set_insert.md to insert.md --- .../terms/insert/{unordered_set_insert.md => insert.md} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename content/cpp/concepts/unordered-set/terms/insert/{unordered_set_insert.md => insert.md} (99%) diff --git a/content/cpp/concepts/unordered-set/terms/insert/unordered_set_insert.md b/content/cpp/concepts/unordered-set/terms/insert/insert.md similarity index 99% rename from content/cpp/concepts/unordered-set/terms/insert/unordered_set_insert.md rename to content/cpp/concepts/unordered-set/terms/insert/insert.md index 0459ab43722..23ba9eed24b 100644 --- a/content/cpp/concepts/unordered-set/terms/insert/unordered_set_insert.md +++ b/content/cpp/concepts/unordered-set/terms/insert/insert.md @@ -205,4 +205,4 @@ The operation fails, and the returned `bool` in the result pair is `false`. Only if a rehash occurs when inserting (for example, after exceeding the load factor threshold). **Q: What’s the time complexity of `insert()`?** -Average: **O(1)**; Worst case: **O(n)** when hash collisions occur. \ No newline at end of file +Average: **O(1)**; Worst case: **O(n)** when hash collisions occur. From 5e9824082598c6637e9b45a5912c6df5b72cc613 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 3 Dec 2025 18:25:05 +0530 Subject: [PATCH 3/3] Refactor insert() documentation for clarity Updated formatting and improved clarity of the 'insert()' documentation for unordered_set. Adjusted titles, descriptions, and examples for consistency. --- .../unordered-set/terms/insert/insert.md | 102 ++++++------------ 1 file changed, 32 insertions(+), 70 deletions(-) diff --git a/content/cpp/concepts/unordered-set/terms/insert/insert.md b/content/cpp/concepts/unordered-set/terms/insert/insert.md index 23ba9eed24b..a2c9cf19d96 100644 --- a/content/cpp/concepts/unordered-set/terms/insert/insert.md +++ b/content/cpp/concepts/unordered-set/terms/insert/insert.md @@ -1,69 +1,45 @@ --- -Title: insert() -Description: Inserts element(s) into an unordered_set if they do not already exist. +Title: 'insert()' +Description: 'Inserts element(s) into an unordered_set if they do not already exist.' Subjects: - - Code Foundations - - Computer Science -tags: - - Data Structures - - Methods - - Sets + - 'Code Foundations' + - 'Computer Science' +Tags: + - 'Data Structures' + - 'Methods' + - 'Sets' CatalogContent: - - learn-c-plus-plus - - paths/computer-science + - 'learn-c-plus-plus' + - 'paths/computer-science' --- -The **`insert()`** member function of C++’s `std::unordered_set` attempts to insert one or more new elements into the container **only if** an equivalent element does not already exist. `unordered_set` stores unique elements and uses a **hash table** for fast lookups, insertions, and deletions. - -Internally, each element’s key is transformed by a **hash function** into a bucket index. When multiple elements hash to the same bucket — known as a **hash collision** — they are grouped together within that bucket. Although average insertion and lookup are constant time (`O(1)`), heavy collisions can cause performance to degrade to linear time (`O(n)`). +The **`insert()`** member function of `std::unordered_set` adds new elements only when no equivalent element is already present. The container stores unique values and uses a hash table for fast lookups, insertions, and deletions. ## Syntax -```cpp -// Single element insertion (copy) -std::pair insert(const value_type& value); - -// Single element insertion (move) -std::pair insert(value_type&& value); - -// Hint insertion (ignored for unordered containers) -iterator insert(const_iterator hint, const value_type& value); - -// Range insertion -void insert(InputIterator first, InputIterator last); - -// Initializer list insertion -void insert(std::initializer_list ilist); - -// Node handle insertion (C++17) -insert_return_type insert(node_type&& nh); -iterator insert(const_iterator hint, node_type&& nh); +```pseudo +unordered_set_name.insert(value); ``` -**Parameters** +Or, alternatively: -| Parameter | Description | -| ------------- | ---------------------------------------------------------------------- | -| `value` | The element to be inserted. | -| `hint` | Iterator hint suggesting where to insert the element (may be ignored). | -| `first, last` | Input iterators defining a range of elements to insert. | -| `ilist` | Initializer list of elements to insert. | -| `nh` | Node handle extracted from another unordered container. | - -**Return Value** +```pseudo +unordered_set_name.insert(first, last); +``` -- Returns a `std::pair`: +**Parameters:** - - `iterator`: Points to the inserted element, or to the existing element if no insertion occurred. - - `bool`: `true` if insertion took place, `false` if the element already existed. +- `value`: The element to insert. +- `first`, `last`: Input iterators that define a range of elements to insert. -For range and initializer list overloads, the return type is `void`. +**Return value:** -**Note: Move Semantics** +- For a single value, the function returns a pair containing an iterator to the element and a boolean that indicates whether the insertion happened. +- For a range, the function returns `void`. -When calling `insert()`` with std::move(obj), the function may take advantage of move semantics to transfer resources from obj instead of copying them. This uses the rvalue reference overload `value_type&& value` which can improve performance when inserting large objects, because it reuses existing resources (like memory buffers) rather than duplicating them. However, if the insertion fails because the element already exists, the state of the moved-from object (obj) is valid but unspecified — it may be empty or altered. +## Example 1: Basic `insert()` Usage -## Example 1: Basic `insert()` Usage - Library Book Catalog +In this example, `insert()` adds book titles and prevents duplicates: ```cpp #include @@ -93,7 +69,7 @@ int main() { } ``` -**Output:** +The output of this code is: ```shell Added: The Hobbit @@ -105,10 +81,12 @@ Books in catalog: - The Hobbit ``` -This example models a simple library catalog where each title must be unique. `unordered_set::insert()` prevents duplicate titles from being added, demonstrating how the container automatically enforces uniqueness while allowing constant-time average insertion. +This example models a library catalog where each title must be unique. `unordered_set::insert()` prevents duplicate titles from being added, demonstrating how the container automatically enforces uniqueness while allowing constant-time average insertion. ## Example 2: Managing Unique Usernames +In this example, `insert()` prevents duplicate usernames from being added: + ```cpp #include #include @@ -140,7 +118,7 @@ int main() { } ``` -**Output:** +The output of this code is: ```shell Username 'mighty_meat' added successfully. @@ -157,10 +135,10 @@ Current registered users: - bilbo_baggins ``` -This example models a login system where usernames must remain unique. The `insert()` method ensures that duplicates are automatically rejected. - ## Codebyte Example: Word Filter with `insert()` +In this example, the program collects only unique words: + ```codebyte/cpp #include #include @@ -190,19 +168,3 @@ int main() { return 0; } ``` - -This example acts as a word collector that keeps only unique entries. Each attempt to insert a duplicate word is automatically rejected by the `unordered_set`. - -## FAQ - -**Q: How does `insert()` differ from `emplace()`?** -`insert()` inserts an existing object, while `emplace()` constructs it directly in-place using provided arguments—often more efficient. - -**Q: What happens if I insert a duplicate element?** -The operation fails, and the returned `bool` in the result pair is `false`. - -**Q: Can `insert()` invalidate iterators?** -Only if a rehash occurs when inserting (for example, after exceeding the load factor threshold). - -**Q: What’s the time complexity of `insert()`?** -Average: **O(1)**; Worst case: **O(n)** when hash collisions occur.