C++ .emplace()
Published Apr 1, 2025
Contribute to Docs
The .emplace() method in C++ for std::map efficiently constructs and inserts an element directly into the map. Unlike .insert(), .emplace() constructs the element in-place, avoiding unnecessary copies or moves.
Syntax
mapName.emplace(key, value)
mapName: Refers to the specific map being modified.key: The key for the new element.value: The value associated with the key.
Example
This example demonstrates using the .emplace() method to add elements to a map and the behaviour on inserting elements with the same key:
#include <iostream>#include <map>#include <string>int main() {// Initialize a map of products and their pricesstd::map<std::string, double> product_prices;// Using std::pair instead of structured binding to support C++11 and laterstd::pair<std::map<std::string, double>::iterator, bool> prod1 = product_prices.emplace("Laptop", 999.99);std::pair<std::map<std::string, double>::iterator, bool> prod2 = product_prices.emplace("Phone", 499.99);std::pair<std::map<std::string, double>::iterator, bool> prod3 = product_prices.emplace("Laptop", 799.99);// Print resultsstd::cout << "Laptop insertion (first attempt): " << (prod1.second ? "Successful" : "Failed") << std::endl;std::cout << "Phone insertion: " << (prod2.second ? "Successful" : "Failed") << std::endl;std::cout << "Laptop insertion (second attempt): " << (prod3.second ? "Successful" : "Failed") << std::endl;// Print the content of the mapfor (const auto& pair : product_prices) {std::cout << pair.first << ": $" << pair.second << std::endl;}return 0;}
The code above results in the following output:
Laptop insertion (first attempt): SuccessfulPhone insertion: SuccessfulLaptop insertion (second attempt): FailedLaptop: $999.99Phone: $499.99
Codebyte Example
Run the following codebyte example to understand how the .emplace() method adds new elements to a map:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours