Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
priority_queue::swap() in C++ STL
Next article icon

priority_queue emplace() in C++ STL

Last Updated : 14 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the smallest element at the top by simply passing an extra parameter while creating the priority queue.

priority_queue::emplace()


This function is used to insert a new element into the priority queue container, the new element is added to the priority queue according to its priority. It is similar to push operation. The difference is that emplace() operation saves unnecessary copy of the object.

Time complexity: O(log n)

Syntax :  

priorityqueuename.emplace(value) Parameters : The element to be inserted into the priority queue is passed as the parameter. Result : The parameter is added to the priority queue at the top position.


Examples: 

Input  : mypqueue{5, 4};          mypqueue.emplace(6); Output : mypqueue = 6, 5, 4  Input  : mypqueue{};          mypqueue.emplace(4); Output : mypqueue = 4


Note: In priority_queue container, the elements are printed in reverse order because the top is printed first then moving on to other elements.

Errors and Exceptions 
1. It has a strong exception guarantee, therefore, no changes are made if an exception is thrown. 
2. Parameter should be of same type as that of the container, otherwise an error is thrown.

C++
// INTEGER PRIORITY QUEUE // CPP program to illustrate // Implementation of emplace() function #include <iostream> #include <queue> using namespace std;  int main() {     priority_queue<int> mypqueue;     mypqueue.emplace(1);     mypqueue.emplace(2);     mypqueue.emplace(3);     mypqueue.emplace(4);     mypqueue.emplace(5);     mypqueue.emplace(6);     // queue becomes 1, 2, 3, 4, 5, 6      // printing the priority queue     cout << "mypqueue = ";     while (!mypqueue.empty()) {         cout << mypqueue.top() << " ";         mypqueue.pop();     }      return 0; } 

Output
mypqueue = 6 5 4 3 2 1 
C++
// CHARACTER PRIORITY QUEUE // CPP program to illustrate // Implementation of emplace() function #include <iostream> #include <queue> using namespace std;  int main() {     priority_queue<char> mypqueue;     mypqueue.emplace('A');     mypqueue.emplace('b');     mypqueue.emplace('C');     mypqueue.emplace('d');     mypqueue.emplace('E');     mypqueue.emplace('f');     // queue becomes A, b, C, d, E, f      // printing the priority queue     cout << "mypqueue = ";     while (!mypqueue.empty()) {         cout << mypqueue.top() << " ";         mypqueue.pop();     }      return 0; } 

Output
mypqueue = f d b E C A 
C++
// STRING PRIORITY QUEUE // CPP program to illustrate // Implementation of emplace() function #include <iostream> #include <queue> #include <string> using namespace std;  int main() {     priority_queue<string> mypqueue;     mypqueue.emplace("portal");     mypqueue.emplace("computer science");     mypqueue.emplace("is a");     mypqueue.emplace("GEEKSFORGEEKS");     // queue becomes portal, computer science,     // is a, GEEKSFORGEEKS      // printing the priority queue     cout << "mypqueue = ";     while (!mypqueue.empty()) {         cout << mypqueue.top() << " ";         mypqueue.pop();     }      return 0; } 

Output
mypqueue = portal is a computer science GEEKSFORGEEKS 

Application : 
Given a number of integers, add them to the priority queue using emplace() and find the size of the priority queue. 

Input : 5, 13, 0, 9, 4 Output: 5


Algorithm 
1. Insert the given elements to the priority queue container one by one using emplace(). 
2. Keep popping the elements of priority queue until it becomes empty, and increment the counter variable. 
3. Print the counter variable.

C++
// CPP program to illustrate // Application of emplace() function #include <iostream> #include <queue> using namespace std;  int main() {     int c = 0;      // Empty Priority Queue     priority_queue<int> pqueue;      // inserting elements into priority_queue     pqueue.emplace(5);     pqueue.emplace(13);     pqueue.emplace(0);     pqueue.emplace(9);     pqueue.emplace(4);      // Priority queue becomes 13, 9, 5, 4, 0      // Counting number of elements in queue     while (!pqueue.empty()) {         pqueue.pop();         c++;     }     cout << c; } 

Output
5

emplace() vs push() 
When we use push(), we create an object and then insert it into the priority_queue. With emplace(), the object is constructed in-place and saves an unnecessary copy. Please see emplace vs insert in C++ STL for details.

C++
// C++ code to demonstrate difference between // emplace and insert #include<bits/stdc++.h> using namespace std;    int main() {     // declaring priority queue     priority_queue<pair<char, int>> pqueue;            // using emplace() to insert pair in-place     pqueue.emplace('a', 24);            // Below line would not compile     // pqueue.push('b', 25);                // using push() to insert pair      pqueue.push(make_pair('b', 25));                // printing the priority_queue     while (!pqueue.empty()) {         pair<char, int> p =  pqueue.top();         cout << p.first << " "              << p.second << endl;         pqueue.pop();     }        return 0; } 

Output
b 25 a 24

Next Article
priority_queue::swap() in C++ STL

A

AyushSaxena
Improve
Article Tags :
  • Misc
  • C++
  • STL
  • cpp-priority-queue
Practice Tags :
  • CPP
  • Misc
  • STL

Similar Reads

    Priority Queue in C++ STL
    In C++, priority queue is a type of queue in which there is some priority assigned to the elements. According to this priority, elements are removed from the queue. By default, the value of the element being inserted is considered as priority. Higher its value, higher its priority. But this can be c
    6 min read
    priority_queue::push() and priority_queue::pop() in C++ STL
    In C++, priority_queue::push() and priority_queue::pop() methods are used to insert and delete the element from the priority_queue container. They both are the member functions of std::priority_queue class defined inside <queue> header file. In this article, we will learn about priority_queue:
    2 min read
    priority_queue::top() in C++ STL
    Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. In general, elements are arranged according to some priority. However in C++ STL, the top element is the greatest elem
    3 min read
    priority_queue::empty() and priority_queue::size() in C++ STL
    Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the sma
    4 min read
    priority_queue emplace() in C++ STL
    Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the sma
    4 min read
    priority_queue::swap() in C++ STL
    Priority queues are a type of container adaptors, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue. However, in C++ STL (by default) the largest element is at the top. We can also create a priority queue having the sma
    3 min read
    priority_queue value_type in C++ STL
    The priority_queue :: value_type method is a built-in function in C++ STL which represents the type of object stored as an element in a priority_queue. It acts as a synonym for the template parameter. Time complexity: O(1)Syntax: priority_queue::value_type variable_name It has no parameters and no r
    2 min read
    Priority Queue of Sets in C++ with Examples
    Priority Queues Priority queues are a type of container adapters, specifically designed such that the first element of the queue is the greatest of all elements in the queue and elements are in nonincreasing order (hence we can see that each element of the queue has a priority {fixed order}). Functi
    4 min read
    Priority queue of pairs in C++ with ordering by first and second element
    Priority Queue: Priority queue is the extension of the queue in which elements associated with priority and elements having higher priority is popped first. Priority queue can contain elements with various data types such as integer, pair of integers, custom data type. But one thing is common that t
    5 min read
    Multiple comparisons in a C++ priority queue?
    What is a Priority Queue? A Priority Queue is an abstract data type that is similar to a queue, and every element has some priority value associated with it. The priority of the elements in a priority queue determines the order in which elements are served (i.e., the order in which they are removed)
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences