From 11a47429eac312ad81d74e886434c468c10231e6 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Sun, 24 Aug 2025 14:17:59 +0530 Subject: [PATCH 1/5] [Term Entry] C++ Sets: emplace() --- .../concepts/sets/terms/emplace/emplace.md | 216 ++++++++++++++++++ 1 file changed, 216 insertions(+) create mode 100644 content/cpp/concepts/sets/terms/emplace/emplace.md diff --git a/content/cpp/concepts/sets/terms/emplace/emplace.md b/content/cpp/concepts/sets/terms/emplace/emplace.md new file mode 100644 index 00000000000..45e86fdd9e6 --- /dev/null +++ b/content/cpp/concepts/sets/terms/emplace/emplace.md @@ -0,0 +1,216 @@ +--- +Title: 'emplace()' +Description: 'Constructs and inserts a new element directly into the set using in-place construction' +Subjects: + - 'Code Foundations' + - 'Computer Science' +Tags: + - 'Data Structures' + - 'Methods' + - 'Sets' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +The **`emplace()`** method is a member function of the C++ `std::set` container that constructs and inserts a new element directly into the set. Unlike traditional insertion methods, `emplace()` constructs the element in-place using the provided arguments, avoiding unnecessary copy or move operations and improving performance by eliminating temporary object creation. + +## Syntax + +```pseudo +std::pair emplace(Args&&... args); +``` + +**Parameters:** + +- `args`: Arguments forwarded to the constructor of the element to be constructed and inserted + +**Return value:** + +Returns a `std::pair` consisting of: + +- `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 + +## Example 1: Basic `emplace()` Usage + +This example demonstrates the fundamental usage of `emplace()` with integer elements: + +```cpp +#include +#include + +int main() { + std::set numbers; + + // Insert elements using emplace() + auto result1 = numbers.emplace(10); + auto result2 = numbers.emplace(20); + auto result3 = numbers.emplace(10); // Duplicate element + + // Check insertion results + std::cout << "Inserted 10: " << result1.second << std::endl; + std::cout << "Inserted 20: " << result2.second << std::endl; + std::cout << "Inserted 10 again: " << result3.second << std::endl; + + // Display set contents + std::cout << "Set contains: "; + for (const auto& num : numbers) { + std::cout << num << " "; + } + std::cout << std::endl; + + return 0; +} +``` + +The output of this code is: + +```shell +Inserted 10: 1 +Inserted 20: 1 +Inserted 10 again: 0 +Set contains: 10 20 +``` + +This example shows how `emplace()` constructs elements directly in the set. The first insertion of 10 succeeds, but the second attempt fails because sets only contain unique elements. + +## Example 2: Student Grade Management with `emplace()` + +This example demonstrates using `emplace()` in a real-world scenario for managing student grades: + +```cpp +#include +#include +#include + +struct Student { + std::string name; + int grade; + + Student(const std::string& n, int g) : name(n), grade(g) {} + + // Comparison operator for set ordering + bool operator<(const Student& other) const { + return grade > other.grade; // Higher grades first + } +}; + +int main() { + std::set topStudents; + + // Add students using emplace() - constructs Student objects in-place + auto result1 = topStudents.emplace("Alice", 95); + auto result2 = topStudents.emplace("Bob", 88); + auto result3 = topStudents.emplace("Carol", 92); + auto result4 = topStudents.emplace("Alice", 90); // Same name, different grade + + std::cout << "Students added successfully:" << std::endl; + std::cout << "Alice (95): " << result1.second << std::endl; + std::cout << "Bob (88): " << result2.second << std::endl; + std::cout << "Carol (92): " << result3.second << std::endl; + std::cout << "Alice (90): " << result4.second << std::endl; + + // Display top students (sorted by grade descending) + std::cout << "\nTop Students Ranking:" << std::endl; + int rank = 1; + for (const auto& student : topStudents) { + std::cout << rank++ << ". " << student.name + << " (Grade: " << student.grade << ")" << std::endl; + } + + return 0; +} +``` + +The output of this code is: + +```shell +Students added successfully: +Alice (95): 1 +Bob (88): 1 +Carol (92): 1 +Alice (90): 1 + +Top Students Ranking: +1. Alice (Grade: 95) +2. Carol (Grade: 92) +3. Bob (Grade: 88) +4. Alice (Grade: 90) +``` + +This example shows how `emplace()` can efficiently construct complex objects directly in the set, avoiding the overhead of creating temporary `Student` objects. + +## Codebyte Example: Product Inventory System with `emplace()` + +This example demonstrates using `emplace()` for managing a product inventory system with unique product codes: + +```cpp +#include +#include +#include +#include + +struct Product { + std::string code; + std::string name; + double price; + + Product(const std::string& c, const std::string& n, double p) + : code(c), name(n), price(p) {} + + // Products are ordered by code for efficient lookup + bool operator<(const Product& other) const { + return code < other.code; + } +}; + +int main() { + std::set inventory; + + // Add products using emplace() - avoids creating temporary Product objects + std::cout << "Adding products to inventory:" << std::endl; + + auto laptop = inventory.emplace("LAP001", "Gaming Laptop", 1299.99); + auto mouse = inventory.emplace("MOU001", "Wireless Mouse", 79.99); + auto keyboard = inventory.emplace("KEY001", "Mechanical Keyboard", 149.99); + auto duplicate = inventory.emplace("LAP001", "Office Laptop", 899.99); + + std::cout << "Gaming Laptop added: " << laptop.second << std::endl; + std::cout << "Wireless Mouse added: " << mouse.second << std::endl; + std::cout << "Mechanical Keyboard added: " << keyboard.second << std::endl; + std::cout << "Duplicate laptop code: " << duplicate.second << std::endl; + + // Display inventory sorted by product code + std::cout << "\nCurrent Inventory:" << std::endl; + std::cout << std::left << std::setw(8) << "Code" + << std::setw(20) << "Name" + << std::right << std::setw(10) << "Price" << std::endl; + std::cout << std::string(38, '-') << std::endl; + + for (const auto& product : inventory) { + std::cout << std::left << std::setw(8) << product.code + << std::setw(20) << product.name + << std::right << std::setw(10) << std::fixed + << std::setprecision(2) << "$" << product.price << std::endl; + } + + return 0; +} +``` + +This example illustrates how `emplace()` ensures product code uniqueness in an inventory system, preventing duplicate entries while maintaining efficient sorted order. + +## Frequently Asked Questions + +### 1. What's the difference between `emplace()` and `insert()`? + +`emplace()` constructs the element in-place using the provided arguments, while `insert()` requires an already constructed object. `emplace()` can be more efficient as it avoids creating temporary objects. + +### 2. What happens if I try to emplace a duplicate element? + +The `emplace()` operation fails and returns a pair with the iterator pointing to the existing element and `false` indicating no insertion occurred. + +### 3. Can `emplace()` invalidate iterators? + +No, `emplace()` does not invalidate any existing iterators or references in the set. From ceb7444f75133c7d5f52ee3b613646100ea70932 Mon Sep 17 00:00:00 2001 From: Avdhoot <50920321+avdhoottt@users.noreply.github.com> Date: Fri, 26 Sep 2025 14:43:14 +0530 Subject: [PATCH 2/5] Update content/cpp/concepts/sets/terms/emplace/emplace.md --- content/cpp/concepts/sets/terms/emplace/emplace.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/cpp/concepts/sets/terms/emplace/emplace.md b/content/cpp/concepts/sets/terms/emplace/emplace.md index 45e86fdd9e6..ce705bb187c 100644 --- a/content/cpp/concepts/sets/terms/emplace/emplace.md +++ b/content/cpp/concepts/sets/terms/emplace/emplace.md @@ -15,7 +15,7 @@ CatalogContent: The **`emplace()`** method is a member function of the C++ `std::set` container that constructs and inserts a new element directly into the set. Unlike traditional insertion methods, `emplace()` constructs the element in-place using the provided arguments, avoiding unnecessary copy or move operations and improving performance by eliminating temporary object creation. -## Syntax +## Syntax of C++ `emplace()` ```pseudo std::pair emplace(Args&&... args); From 4866aaf8a7b34f3c222f47847f144105d9cd2387 Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 5 Nov 2025 17:14:24 +0530 Subject: [PATCH 3/5] [Term Entry] C++ Queue: emplace() --- .../concepts/queues/terms/emplace/emplace.md | 142 ++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 content/cpp/concepts/queues/terms/emplace/emplace.md diff --git a/content/cpp/concepts/queues/terms/emplace/emplace.md b/content/cpp/concepts/queues/terms/emplace/emplace.md new file mode 100644 index 00000000000..ad2ce6f7b82 --- /dev/null +++ b/content/cpp/concepts/queues/terms/emplace/emplace.md @@ -0,0 +1,142 @@ +--- +Title: 'emplace()' +Description: 'Constructs a new element at the end of the queue in-place using forwarded arguments.' +Subjects: + - 'Code Foundations' + - 'Computer Science' +Tags: + - 'Containers' + - 'Methods' + - 'Queues' +CatalogContent: + - 'learn-c-plus-plus' + - 'paths/computer-science' +--- + +The **`emplace()`** method of the `std::queue` container adaptor constructs a new element directly in the underlying container at the back of the queue, forwarding the provided arguments to the constructor of `T`. Because the object is constructed in place, this can improve performance for types with expensive copy or move operations. + +## Syntax + +```pseudo +queue.emplace(args...) +``` + +**Parameters:** + +- `args…` (variadic template parameters): Arguments forwarded to construct the new element of type `T`. + +**Return value:** + +None (void). The new element is added to the end of the queue, and the queue size increases by one. + +## Example 1: Enqueueing log entries into a queue + +In this example, log messages are constructed in place and enqueued for later processing: + +```cpp +#include +#include +#include + +struct LogEntry { + std::string level; + std::string message; + LogEntry(std::string lvl, std::string msg) + : level(std::move(lvl)), message(std::move(msg)) {} +}; + +int main(){ + std::queue logs; + logs.emplace("INFO", "Application started"); + logs.emplace("WARN", "Low disk space"); + logs.emplace("ERROR", "Out of memory"); + + while(!logs.empty()){ + const auto& entry = logs.front(); + std::cout << "[" << entry.level << "] " << entry.message << "\n"; + logs.pop(); + } +} +``` + +The output of this code is: + +```shell +[INFO] Application started +[WARN] Low disk space +[ERROR] Out of memory +``` + +## Example 2: Constructing tasks in a task queue + +In this example, tasks with multiple constructor parameters are constructed directly inside the queue: + +```cpp +#include +#include +#include + +struct Task { + int id; + std::string description; + Task(int i, std::string desc) + : id(i), description(std::move(desc)) {} + void run() const { std::cout << "Running task #" << id << ": " << description << "\n"; } +}; + +int main(){ + std::queue taskQueue; + taskQueue.emplace(1, "Load configuration"); + taskQueue.emplace(2, "Initialize modules"); + taskQueue.emplace(3, "Start services"); + + while(!taskQueue.empty()){ + taskQueue.front().run(); + taskQueue.pop(); + } +} +``` + +The output of this code is: + +```shell +Running task #1: Load configuration +Running task #2: Initialize modules +Running task #3: Start services +``` + +## Codebyte Example: Buffering sensor data with emplace + +In this example, sensor readings are constructed and enqueued as soon as they arrive, minimizing overhead: + +```codebyte/cpp +#include +#include +#include + +struct SensorData { + int sensorId; + double value; + long timestamp; + SensorData(int id, double val, long ts) + : sensorId(id), value(val), timestamp(ts) {} + void print() const { + std::cout << "Sensor#" << sensorId + << " value=" << value + << " time=" << timestamp << "\n"; + } +}; + +int main(){ + std::queue buffer; + buffer.emplace(101, 23.5, 1617181920L); + buffer.emplace(102, 19.8, 1617181930L); + + while(!buffer.empty()){ + buffer.front().print(); + buffer.pop(); + } + + return 0; +} +``` From 339a9bb9e9a49dc5f52897d2ab7a40ebf09b69aa Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 5 Nov 2025 17:15:45 +0530 Subject: [PATCH 4/5] Delete content/cpp/concepts/sets/terms/emplace/emplace.md --- .../concepts/sets/terms/emplace/emplace.md | 216 ------------------ 1 file changed, 216 deletions(-) delete mode 100644 content/cpp/concepts/sets/terms/emplace/emplace.md diff --git a/content/cpp/concepts/sets/terms/emplace/emplace.md b/content/cpp/concepts/sets/terms/emplace/emplace.md deleted file mode 100644 index ce705bb187c..00000000000 --- a/content/cpp/concepts/sets/terms/emplace/emplace.md +++ /dev/null @@ -1,216 +0,0 @@ ---- -Title: 'emplace()' -Description: 'Constructs and inserts a new element directly into the set using in-place construction' -Subjects: - - 'Code Foundations' - - 'Computer Science' -Tags: - - 'Data Structures' - - 'Methods' - - 'Sets' -CatalogContent: - - 'learn-c-plus-plus' - - 'paths/computer-science' ---- - -The **`emplace()`** method is a member function of the C++ `std::set` container that constructs and inserts a new element directly into the set. Unlike traditional insertion methods, `emplace()` constructs the element in-place using the provided arguments, avoiding unnecessary copy or move operations and improving performance by eliminating temporary object creation. - -## Syntax of C++ `emplace()` - -```pseudo -std::pair emplace(Args&&... args); -``` - -**Parameters:** - -- `args`: Arguments forwarded to the constructor of the element to be constructed and inserted - -**Return value:** - -Returns a `std::pair` consisting of: - -- `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 - -## Example 1: Basic `emplace()` Usage - -This example demonstrates the fundamental usage of `emplace()` with integer elements: - -```cpp -#include -#include - -int main() { - std::set numbers; - - // Insert elements using emplace() - auto result1 = numbers.emplace(10); - auto result2 = numbers.emplace(20); - auto result3 = numbers.emplace(10); // Duplicate element - - // Check insertion results - std::cout << "Inserted 10: " << result1.second << std::endl; - std::cout << "Inserted 20: " << result2.second << std::endl; - std::cout << "Inserted 10 again: " << result3.second << std::endl; - - // Display set contents - std::cout << "Set contains: "; - for (const auto& num : numbers) { - std::cout << num << " "; - } - std::cout << std::endl; - - return 0; -} -``` - -The output of this code is: - -```shell -Inserted 10: 1 -Inserted 20: 1 -Inserted 10 again: 0 -Set contains: 10 20 -``` - -This example shows how `emplace()` constructs elements directly in the set. The first insertion of 10 succeeds, but the second attempt fails because sets only contain unique elements. - -## Example 2: Student Grade Management with `emplace()` - -This example demonstrates using `emplace()` in a real-world scenario for managing student grades: - -```cpp -#include -#include -#include - -struct Student { - std::string name; - int grade; - - Student(const std::string& n, int g) : name(n), grade(g) {} - - // Comparison operator for set ordering - bool operator<(const Student& other) const { - return grade > other.grade; // Higher grades first - } -}; - -int main() { - std::set topStudents; - - // Add students using emplace() - constructs Student objects in-place - auto result1 = topStudents.emplace("Alice", 95); - auto result2 = topStudents.emplace("Bob", 88); - auto result3 = topStudents.emplace("Carol", 92); - auto result4 = topStudents.emplace("Alice", 90); // Same name, different grade - - std::cout << "Students added successfully:" << std::endl; - std::cout << "Alice (95): " << result1.second << std::endl; - std::cout << "Bob (88): " << result2.second << std::endl; - std::cout << "Carol (92): " << result3.second << std::endl; - std::cout << "Alice (90): " << result4.second << std::endl; - - // Display top students (sorted by grade descending) - std::cout << "\nTop Students Ranking:" << std::endl; - int rank = 1; - for (const auto& student : topStudents) { - std::cout << rank++ << ". " << student.name - << " (Grade: " << student.grade << ")" << std::endl; - } - - return 0; -} -``` - -The output of this code is: - -```shell -Students added successfully: -Alice (95): 1 -Bob (88): 1 -Carol (92): 1 -Alice (90): 1 - -Top Students Ranking: -1. Alice (Grade: 95) -2. Carol (Grade: 92) -3. Bob (Grade: 88) -4. Alice (Grade: 90) -``` - -This example shows how `emplace()` can efficiently construct complex objects directly in the set, avoiding the overhead of creating temporary `Student` objects. - -## Codebyte Example: Product Inventory System with `emplace()` - -This example demonstrates using `emplace()` for managing a product inventory system with unique product codes: - -```cpp -#include -#include -#include -#include - -struct Product { - std::string code; - std::string name; - double price; - - Product(const std::string& c, const std::string& n, double p) - : code(c), name(n), price(p) {} - - // Products are ordered by code for efficient lookup - bool operator<(const Product& other) const { - return code < other.code; - } -}; - -int main() { - std::set inventory; - - // Add products using emplace() - avoids creating temporary Product objects - std::cout << "Adding products to inventory:" << std::endl; - - auto laptop = inventory.emplace("LAP001", "Gaming Laptop", 1299.99); - auto mouse = inventory.emplace("MOU001", "Wireless Mouse", 79.99); - auto keyboard = inventory.emplace("KEY001", "Mechanical Keyboard", 149.99); - auto duplicate = inventory.emplace("LAP001", "Office Laptop", 899.99); - - std::cout << "Gaming Laptop added: " << laptop.second << std::endl; - std::cout << "Wireless Mouse added: " << mouse.second << std::endl; - std::cout << "Mechanical Keyboard added: " << keyboard.second << std::endl; - std::cout << "Duplicate laptop code: " << duplicate.second << std::endl; - - // Display inventory sorted by product code - std::cout << "\nCurrent Inventory:" << std::endl; - std::cout << std::left << std::setw(8) << "Code" - << std::setw(20) << "Name" - << std::right << std::setw(10) << "Price" << std::endl; - std::cout << std::string(38, '-') << std::endl; - - for (const auto& product : inventory) { - std::cout << std::left << std::setw(8) << product.code - << std::setw(20) << product.name - << std::right << std::setw(10) << std::fixed - << std::setprecision(2) << "$" << product.price << std::endl; - } - - return 0; -} -``` - -This example illustrates how `emplace()` ensures product code uniqueness in an inventory system, preventing duplicate entries while maintaining efficient sorted order. - -## Frequently Asked Questions - -### 1. What's the difference between `emplace()` and `insert()`? - -`emplace()` constructs the element in-place using the provided arguments, while `insert()` requires an already constructed object. `emplace()` can be more efficient as it avoids creating temporary objects. - -### 2. What happens if I try to emplace a duplicate element? - -The `emplace()` operation fails and returns a pair with the iterator pointing to the existing element and `false` indicating no insertion occurred. - -### 3. Can `emplace()` invalidate iterators? - -No, `emplace()` does not invalidate any existing iterators or references in the set. From 9aad220da96e02ebd66a3f833f98cefe2015898e Mon Sep 17 00:00:00 2001 From: Mamta Wardhani Date: Wed, 5 Nov 2025 17:16:34 +0530 Subject: [PATCH 5/5] Update emplace.md --- content/cpp/concepts/queues/terms/emplace/emplace.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/cpp/concepts/queues/terms/emplace/emplace.md b/content/cpp/concepts/queues/terms/emplace/emplace.md index ad2ce6f7b82..ad43cbd3e4a 100644 --- a/content/cpp/concepts/queues/terms/emplace/emplace.md +++ b/content/cpp/concepts/queues/terms/emplace/emplace.md @@ -23,7 +23,7 @@ queue.emplace(args...) **Parameters:** -- `args…` (variadic template parameters): Arguments forwarded to construct the new element of type `T`. +- `args...` (variadic template parameters): Arguments forwarded to construct the new element of type `T`. **Return value:**