🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 35 (from laksa076)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

đź“„
INDEXABLE
âś…
CRAWLED
4 days ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.2 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://www.udacity.com/blog/2020/03/c-queues-explained.html
Last Crawled2026-04-08 11:42:40 (4 days ago)
First Indexed2021-03-05 16:18:32 (5 years ago)
HTTP Status Code200
Meta TitleQueue in C++ Explained with Examples | Udacity
Meta DescriptionWhat is queue in C++ and how should you use it? Learn queue C++ best practices, including use cases and examples.
Meta Canonicalnull
Boilerpipe Text
Start Learning Imagine you’re in line at a lemonade stand on a hot summer day, waiting to reach the front so you can enjoy a refreshing drink. Without having to think about it, you know that the first person to join the line will be the first person to leave it, and the last person to join will be the last to receive a drink.   The same concept exists in programming—in C++ , this built-in data structure is called a queue. In this article, we’ll touch on what queues are and how to use them, and we’ll discuss some circumstances in which you might use and avoid queues.  Photo of administrator responsible for cyber security of large corporation searching for safety gaps debugging existant operating system to reduce hacker attacks success probability What is a queue in C++? A queue is a data structure that is optimized for a specific access pattern: the “first in, first out” (FIFO) pattern that describes lines as we know them in everyday life.  In addition to a garden-variety queue, C++ also has the concept of a priority queue, which you can think of as a structured or organized queue. The top element (largest, greatest, etc.) is always moved to the front of the queue, the bottom element is moved to the back, and each element in between has a priority in relation to all other elements.  C++ has built-in queue and priority_queue data structures. How to use a C++ queue The basic operations available to you when working with queues include creating a new queue, adding elements to it and retrieving elements. Let’s look at how this works with both a FIFO queue and a priority queue. FIFO Queues First, let’s create a queue: #include <iostream> // std::cout #include <queue> // std::queue using namespace std; int main () { queue<int> my_queue; } This creates an empty queue, which we have illustratively named my_queue. Now, how can we add an element to this queue? Since we initialized our queue to contain integers, let’s add one using the push member function. Keep in mind that we need to do this using the same scope in which we declared our queue: my_queue.push(7); Since our queue is empty, the integer 7 will be the only element. But say we push another element—where will it stand in the queue? The answer is that adding an element assigns it the last index, as the newest member of the queue. As far as retrieving elements goes, the front and back functions will return references to those respective elements in the queue. Let’s push another integer into our queue so that the front and back functions will return different integers. my_queue.push(3); my_queue.front(); // returns 7 my_queue.back(); // returns 3 It’s important to note that while we have operations that retrieve elements from the front and back, we don’t have a way to get an element from the middle of a queue. If we push another integer—say, 4—to our queue, we have no way of accessing 3, now in the middle of our queue. Priority Queues Now that you’ve grasped the foundations of C++ queues, let’s look at the same operations in priority queues. Creating a priority queue (and then populating it with a for-loop) looks like this:  #include <iostream> // std::cout #include <queue> // std::queue using namespace std; int main () { priority_queue<int> my_priority_queue; for (int i = 5; i > 0; --i) my_priority_queue.push(i); // adds 5, 4, 3, 2, 1 } Priority queues have most of the same operations as queues have, with a few additions like  top(). The top member function replaces the front member function used for FIFO queues. Note that there is no priority-queue equivalent to the back function.  Say we add this line right after our for-loop: cout << my_priority_queue.top() << endl; What do you think this will print out? If you said 5, you are correct.  What if we changed the order in which elements were pushed into the priority queue, so that the smallest elements are added first? #include <iostream> // std::cout #include <queue> // std::queue int main () { priority_queue<int> my_priority_queue; for (int i = 0; i < 5; ++i) my_priority_queue.push(i + 1); // adds 1, 2, 3, 4, 5 cout << my_priority_queue.top() << endl; } If this were a FIFO queue, we would expect 1 to be the first item, since it was pushed first. However, the code prints out 5 when we call top(). As expected, our priority queue has ordered the elements for us. To check if this is really how priority queues work, let’s now call pop(), a function (also available in FIFO queues) that removes the topmost element and returns its value. With a priority queue, we should see that the numbers returned by pop are ordered, so let’s try it and see:  priority_queue.pop(); // returns 5 priority_queue.pop(); // returns 4 priority_queue.pop(); // returns 3 priority_queue.pop(); // returns 2 priority_queue.pop(); // returns 1 And so we see that this priority queue really is ordered.  Now that we have an understanding of both types of queues, let’s move on to some use cases for these data structures. When to use queues in C++ Queues are great at keeping track of tasks to process and are the right choice if you need to track the order in which items need to be processed. If, for example, a movie studio has a number of scenes to render on its server farm, a queue will effectively keep track of which task came in first and handles it first. Perhaps you don’t need to keep track of the order elements are inserted, but you do need to order tasks according to a certain metric. In this case queues can still be a great fit—priority queues, that is. Back in our movie studio example, some projects will have a higher priority, and a priority queue will help those get taken care of first. When to avoid using queues in C++ As previously noted, we can’t reference queue elements outside of the first and last ones, so if you’re looking for access to, say, the sixth element of a 12-element list, a queue is not the right data structure for you. You might find an array better suited to this purpose. Underlying containers in C++ So far we have only touched on the first argument used in FIFO queues and priority queues. As you know, this first argument specifies the type of elements in the queue, but you can also specify an optional second argument.  A priority queue is a container adapter, which changes the functionality of a given container type by imposing limitations on it. The optional second argument specifies the underlying container that actually stores the elements.   Let’s look at our previous example and add in a second argument: priority_queue<int, vector<int> > my_priority_queue Here, a vector is the underlying container—that is, the priority queue uses a vector container to store its values. It is worthwhile to note that the elements in the underlying container are accessed by the member functions of the container adapter (the priority queue), and not by those of the container (the vector) itself. Remember, the second argument is optional. If none is provided, a FIFO queue defaults to a deque as its container adapter, and a priority queue defaults to a vector. Other underlying container options include a list (for a FIFO queue) and a deque (for a priority queue). Further reading and resources This is a comprehensive overview of member functions available to FIFO queues and priority queues. Here is a great overview of FIFO queues and another for priority queues . Conclusion In this article, we covered what C++ FIFO queues and priority queues are, and we walked through the code for instantiating, adding to and retrieving from these data structures. We went over some ideal circumstances for using queues and talked about when other data structures might be more appropriate. Start Learning
Markdown
[![Udacity](https://www.udacity.com/blog/wp-content/uploads/2024/07/Udacity_Logo_Color_2x-1024x284-1.webp)![Udacity](https://www.udacity.com/blog/wp-content/uploads/2021/12/u-logo-violet.svg)](https://www.udacity.com/) - [Learn](https://www.udacity.com/blog/2020/03/c-queues-explained.html) - - - #### Schools - [Artificial Intelligence](https://www.udacity.com/school/artificial-intelligence) - [Autonomous Systems](https://www.udacity.com/school/autonomous-systems) - [Business](https://www.udacity.com/school/business) - [Career Resources](https://www.udacity.com/school/career-resources) - [Cloud Computing](https://www.udacity.com/school/cloud-computing) - [Cybersecurity](https://www.udacity.com/school/cybersecurity) - [Data Science](https://www.udacity.com/school/data-science) - [Executive Leadership](https://www.udacity.com/school/executive-leadership) - [Programming](https://www.udacity.com/school/programming) - [Product Management](https://www.udacity.com/school/product-management) - - #### Popular - [Data Engineering with AWS](https://www.udacity.com/course/data-engineer-nanodegree--nd027) - [Introduction to Programming](https://www.udacity.com/course/intro-to-programming-nanodegree--nd000) - [C++](https://www.udacity.com/course/c-plus-plus-nanodegree--nd213) - [Business Analytics](https://www.udacity.com/course/business-analytics-nanodegree--nd098) - [Data Analyst](https://www.udacity.com/course/data-analyst-nanodegree--nd002) - [All Programs](https://www.udacity.com/catalog/all/any-price/any-school/any-skill/any-difficulty/any-duration/any-type/most-popular/page-1) - - #### Featured - [Deep Reinforcement Learning](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893) - [Computer Vision](https://www.udacity.com/course/computer-vision-nanodegree--nd891) - [Natural Language Processing](https://www.udacity.com/course/natural-language-processing-nanodegree--nd892) - [Data Structure and Algorithms](https://www.udacity.com/course/data-structures-and-algorithms-nanodegree--nd256) - [Sensor Fusion Engineer](https://www.udacity.com/course/sensor-fusion-engineer-nanodegree--nd313) - [Catalog](https://www.udacity.com/catalog) - [Business](https://www.udacity.com/blog/2020/03/c-queues-explained.html) - [Overview](https://www.udacity.com/enterprise/overview) - [Resources](https://www.udacity.com/resource-center) - [Compare Plans](https://www.udacity.com/enterprise/plans) - [Government](https://www.udacity.com/government/overview) - [Log In](https://auth.udacity.com/sign-in?next=https://www.udacity.com&_gl=1*sgbi1a*_ga*MjA3MjY4NTQzMy4xNjk1Mzk3ODc0*_ga_CF22GKVCFK*MTY5NTM5OTAwNS4xLjEuMTY5NTM5OTYwNy41OC4wLjA.) - [Join For Free](https://auth.udacity.com/sign-up?next=https://www.udacity.com&_gl=1*iks2dj*_ga*ODEwMzc1MDkyLjE3MTIyMzk1MzA.*_ga_CF22GKVCFK*MTcxMjI0NjA1Ni4zLjAuMTcxMjI0NjA1Ni42MC4wLjA.) Cancel Select Page C++ - C++ Queues # C++ Queues Explained March 25, 2020\| 5 min read [Stephen Welch](https://www.udacity.com/blog/author/stephenwelch) [Back](https://www.udacity.com/blog) C++ Queues Explained Share [Start Learning](https://www.udacity.com/course/c-plus-plus-nanodegree--nd213?utm_source=Blog&utm_medium=Blog&utm_campaign=C%2B%2B%20Strings%20Explained&utm_content=blog) Imagine you’re in line at a lemonade stand on a hot summer day, waiting to reach the front so you can enjoy a refreshing drink. Without having to think about it, you know that the first person to join the line will be the first person to leave it, and the last person to join will be the last to receive a drink. The same concept exists in programming—in [C++](https://www.udacity.com/course/c-plus-plus-nanodegree--nd213), this built-in data structure is called a queue. In this article, we’ll touch on what queues are and how to use them, and we’ll discuss some circumstances in which you might use and avoid queues. ![C++ Queues](https://www.udacity.com/blog/wp-content/uploads/2020/04/AdobeStock_298066277.jpeg) Photo of administrator responsible for cyber security of large corporation searching for safety gaps debugging existant operating system to reduce hacker attacks success probability ## What is a queue in C++? A queue is a data structure that is optimized for a specific access pattern: the “first in, first out” (FIFO) pattern that describes lines as we know them in everyday life. In addition to a garden-variety queue, C++ also has the concept of a priority queue, which you can think of as a structured or organized queue. The top element (largest, greatest, etc.) is always moved to the front of the queue, the bottom element is moved to the back, and each element in between has a priority in relation to all other elements. C++ has built-in queue and priority\_queue data structures. ## How to use a C++ queue The basic operations available to you when working with queues include creating a new queue, adding elements to it and retrieving elements. Let’s look at how this works with both a FIFO queue and a priority queue. ### **FIFO Queues** First, let’s create a queue: ``` #include <iostream> // std::cout #include <queue> // std::queue using namespace std; int main () { queue<int> my_queue; } ``` This creates an empty queue, which we have illustratively named my\_queue. Now, how can we add an element to this queue? Since we initialized our queue to contain integers, let’s add one using the push member function. Keep in mind that we need to do this using the same scope in which we declared our queue: ``` my_queue.push(7); ``` Since our queue is empty, the integer 7 will be the only element. But say we push another element—where will it stand in the queue? The answer is that adding an element assigns it the last index, as the newest member of the queue. As far as retrieving elements goes, the front and back functions will return references to those respective elements in the queue. Let’s push another integer into our queue so that the front and back functions will return different integers. ``` my_queue.push(3); my_queue.front(); // returns 7 my_queue.back(); // returns 3 ``` It’s important to note that while we have operations that retrieve elements from the front and back, we don’t have a way to get an element from the middle of a queue. If we push another integer—say, 4—to our queue, we have no way of accessing 3, now in the middle of our queue. ### **Priority Queues** Now that you’ve grasped the foundations of C++ queues, let’s look at the same operations in priority queues. Creating a priority queue (and then populating it with a for-loop) looks like this: ``` #include <iostream> // std::cout #include <queue> // std::queue using namespace std; int main () { priority_queue<int> my_priority_queue; for (int i = 5; i > 0; --i) my_priority_queue.push(i); // adds 5, 4, 3, 2, 1 } ``` Priority queues have most of the same operations as queues have, with a few additions like top(). The top member function replaces the front member function used for FIFO queues. Note that there is no priority-queue equivalent to the back function. Say we add this line right after our for-loop: ``` cout << my_priority_queue.top() << endl; ``` What do you think this will print out? If you said 5, you are correct. What if we changed the order in which elements were pushed into the priority queue, so that the smallest elements are added first? ``` #include <iostream> // std::cout #include <queue> // std::queue int main () { priority_queue<int> my_priority_queue; for (int i = 0; i < 5; ++i) my_priority_queue.push(i + 1); // adds 1, 2, 3, 4, 5 cout << my_priority_queue.top() << endl; } ``` If this were a FIFO queue, we would expect 1 to be the first item, since it was pushed first. However, the code prints out 5 when we call top(). As expected, our priority queue has ordered the elements for us. To check if this is really how priority queues work, let’s now call pop(), a function (also available in FIFO queues) that removes the topmost element and returns its value. With a priority queue, we should see that the numbers returned by pop are ordered, so let’s try it and see: ``` priority_queue.pop(); // returns 5 priority_queue.pop(); // returns 4 priority_queue.pop(); // returns 3 priority_queue.pop(); // returns 2 priority_queue.pop(); // returns 1 ``` And so we see that this priority queue really is ordered. Now that we have an understanding of both types of queues, let’s move on to some use cases for these data structures. ## When to use queues in C++ Queues are great at keeping track of tasks to process and are the right choice if you need to track the order in which items need to be processed. If, for example, a movie studio has a number of scenes to render on its server farm, a queue will effectively keep track of which task came in first and handles it first. Perhaps you don’t need to keep track of the order elements are inserted, but you do need to order tasks according to a certain metric. In this case queues can still be a great fit—priority queues, that is. Back in our movie studio example, some projects will have a higher priority, and a priority queue will help those get taken care of first. ## When to avoid using queues in C++ As previously noted, we can’t reference queue elements outside of the first and last ones, so if you’re looking for access to, say, the sixth element of a 12-element list, a queue is not the right data structure for you. You might find an array better suited to this purpose. ## Underlying containers in C++ So far we have only touched on the first argument used in FIFO queues and priority queues. As you know, this first argument specifies the type of elements in the queue, but you can also specify an optional second argument. A priority queue is a container adapter, which changes the functionality of a given container type by imposing limitations on it. The optional second argument specifies the underlying container that actually stores the elements. Let’s look at our previous example and add in a second argument: ``` priority_queue<int, vector<int> > my_priority_queue ``` Here, a [vector](https://www.cplusplus.com/reference/vector/vector/vector/) is the underlying container—that is, the priority queue uses a vector container to store its values. It is worthwhile to note that the elements in the underlying container are accessed by the member functions of the container adapter (the priority queue), and not by those of the container (the vector) itself. Remember, the second argument is optional. If none is provided, a FIFO queue defaults to a [deque](https://www.cplusplus.com/reference/deque/deque/) as its container adapter, and a priority queue defaults to a vector. Other underlying container options include a list (for a FIFO queue) and a deque (for a priority queue). ## Further reading and resources This is a [comprehensive overview](https://www.tutorialspoint.com/cpp_standard_library/queue.htm) of member functions available to FIFO queues and priority queues. Here is a [great overview](http://www.cplusplus.com/reference/queue/queue/) [of](http://www.cplusplus.com/reference/queue/queue/) FIFO [queues](http://www.cplusplus.com/reference/queue/queue/) and another for [priority queues](http://www.cplusplus.com/reference/queue/priority_queue/). ## Conclusion In this article, we covered what C++ FIFO queues and priority queues are, and we walked through the code for instantiating, adding to and retrieving from these data structures. We went over some ideal circumstances for using queues and talked about when other data structures might be more appropriate. [Start Learning](https://www.udacity.com/course/c-plus-plus-nanodegree--nd213?utm_source=Blog&utm_medium=Blog&utm_campaign=C%2B%2B%20Strings%20Explained&utm_content=blog) ![Stephen Welch](https://www.udacity.com/blog/wp-content/uploads/2020/02/Stephen-Welch-compress.jpg) Stephen Welch Stephen is a Content Developer at Udacity and has built the C++ and Self-Driving Car Engineer Nanodegree programs. He started teaching and coding while completing a Ph.D. in mathematics, and has been passionate about engineering education ever since. [View All Posts by Stephen Welch](https://www.udacity.com/blog/author/stephenwelch) ###### Popular Nanodegrees [Programming for Data Science with Python](https://www.udacity.com/course/programming-for-data-science-nanodegree--nd104) [Data Scientist Nanodegree](https://www.udacity.com/course/data-scientist-nanodegree--nd025) [Self-Driving Car Engineer](https://www.udacity.com/course/self-driving-car-engineer-nanodegree--nd013) [Data Analyst Nanodegree](https://www.udacity.com/course/data-analyst-nanodegree--nd002) [Android Basics Nanodegree](https://www.udacity.com/course/android-basics-nanodegree-by-google--nd803) [Intro to Programming Nanodegree](https://www.udacity.com/course/intro-to-programming-nanodegree--nd000) [AI for Trading](https://www.udacity.com/course/ai-for-trading--nd880) [Predictive Analytics for Business Nanodegree](https://www.udacity.com/course/predictive-analytics-for-business-nanodegree--nd008t) [AI For Business Leaders](https://www.udacity.com/course/ai-for-business-leaders--nd054) [Data Structures & Algorithms](https://www.udacity.com/course/data-structures-and-algorithms-nanodegree--nd256) [School of Artificial Intelligence](https://www.udacity.com/enterprise/artificial-intelligence) [School of Cyber Security](https://www.udacity.com/enterprise/cybersecurity) [School of Data Science](https://www.udacity.com/enterprise/data-science) [School of Business](https://www.udacity.com/enterprise/business) [School of Autonomous Systems](https://www.udacity.com/enterprise/autonomous-systems) [School of Executive Leadership](https://www.udacity.com/enterprise/executive-leadership) [School of Programming and Development](https://www.udacity.com/enterprise/programming) ###### Related Articles [![](https://www.udacity.com/blog/wp-content/uploads/2025/11/Java-OOP-Explained@2x-378x212.jpg.webp)](https://www.udacity.com/blog/2025/11/java-oop-explained-principles-examples-and-best-practices.html "Link for <strong>Java OOP Explained: Principles, Examples, and Best Practices</strong>") #### [**Java OOP Explained: Principles, Examples, and Best Practices**](https://www.udacity.com/blog/2025/11/java-oop-explained-principles-examples-and-best-practices.html "<strong>Java OOP Explained: Principles, Examples, and Best Practices</strong>") When I first began experimenting with Java, I considered it a more sophisticated version of the simple... [![]()](https://www.udacity.com/blog/2025/09/visual-studio-code-tutorial-for-beginners-productivity-tips-and-extensions.html "Link for <strong>Visual Studio Code Tutorial for Beginners: Productivity Tips and Extensions</strong>") #### [**Visual Studio Code Tutorial for Beginners: Productivity Tips and Extensions**](https://www.udacity.com/blog/2025/09/visual-studio-code-tutorial-for-beginners-productivity-tips-and-extensions.html "<strong>Visual Studio Code Tutorial for Beginners: Productivity Tips and Extensions</strong>") When I first started coding, I bounced between different text editors like a pinball, never quite finding... [![]()](https://www.udacity.com/blog/2025/09/async-await-in-javascript-simplify-asynchronous-code-with-practical-examples.html "Link for Async/Await in JavaScript: Simplify Asynchronous Code with Practical Examples") #### [Async/Await in JavaScript: Simplify Asynchronous Code with Practical Examples](https://www.udacity.com/blog/2025/09/async-await-in-javascript-simplify-asynchronous-code-with-practical-examples.html "Async/Await in JavaScript: Simplify Asynchronous Code with Practical Examples") A while ago when I first tried to do things asynchronously with JavaScript, things got overwhelming fast.... [![](https://www.udacity.com/blog/wp-content/uploads/2025/06/How-to-Build-a-Modern-Login-Page-with-HTML-and-CSS-378x212.png.webp)](https://www.udacity.com/blog/2025/06/how-to-build-a-modern-login-page-with-html-and-css.html "Link for How to Build a Modern Login Page with HTML and CSS") #### [How to Build a Modern Login Page with HTML and CSS](https://www.udacity.com/blog/2025/06/how-to-build-a-modern-login-page-with-html-and-css.html "How to Build a Modern Login Page with HTML and CSS") Quite some time ago, when I first designed a login page, I treated it as a simple... [css,](https://www.udacity.com/blog/search/label/css) [HTML](https://www.udacity.com/blog/search/label/html) ![Site Footer Logo](https://www.udacity.com/blog/wp-content/uploads/2024/07/Udacity_Logo_Color_2x-1024x284-1.webp) #### Company - [About](https://www.udacity.com/about-us) - [Why Udacity?](https://www.udacity.com/experience) - [Blog](https://www.udacity.com/blog?_gl=1*1o0u9yl*_ga*ODEwMzc1MDkyLjE3MTIyMzk1MzA.*_ga_CF22GKVCFK*MTcxMjI0ODQ5NC40LjAuMTcxMjI0ODQ5NC42MC4wLjA.) - [In the News](https://www.udacity.com/news) - [Jobs at Udacity](https://www.udacity.com/jobs?_gl=1*1o0u9yl*_ga*ODEwMzc1MDkyLjE3MTIyMzk1MzA.*_ga_CF22GKVCFK*MTcxMjI0ODQ5NC40LjAuMTcxMjI0ODQ5NC42MC4wLjA.) #### Resources - [Catalog](https://www.udacity.com/catalog) - [Help and FAQ](https://support.udacity.com/hc/en-us?_gl=1*w7u3yb*_ga*ODEwMzc1MDkyLjE3MTIyMzk1MzA.*_ga_CF22GKVCFK*MTcxMjI0ODQ5NC40LjAuMTcxMjI0ODQ5NC42MC4wLjA.) - [Scholarships](https://www.udacity.com/scholarships) #### Udacity Schools - [School of Artificial Intelligence](https://www.udacity.com/school/artificial-intelligence) - [School of Autonomous Systems](https://www.udacity.com/school/autonomous-systems) - [School of Business](https://www.udacity.com/school/business) - [School of Cloud Computing](https://www.udacity.com/school/cloud-computing) - [School of Cybersecurity](https://www.udacity.com/school/cybersecurity) - [School of Data Science](https://www.udacity.com/school/data-science) - [School of Product Management](https://www.udacity.com/school/product-management) - [School of Programming](https://www.udacity.com/school-of-programming) #### Featured Programs - [Business Analytics](https://www.udacity.com/course/business-analytics-nanodegree--nd098) - [SQL](https://www.udacity.com/course/learn-sql--nd072) - [AWS Cloud Architect](https://www.udacity.com/course/aws-cloud-architect-nanodegree--nd063) - [Data Analyst](https://www.udacity.com/course/data-analyst-nanodegree--nd002) - [Intro to Programming](https://www.udacity.com/course/intro-to-programming-nanodegree--nd000) - [Digital Marketing](https://www.udacity.com/course/digital-marketing-nanodegree--nd018) - [Self Driving Car Engineer](https://www.udacity.com/course/self-driving-car-engineer-nanodegree--nd0013) #### Only at Udacity - [Artificial Intelligence](https://www.udacity.com/course/ai-artificial-intelligence-nanodegree--nd898) - [Deep Learning](https://www.udacity.com/course/deep-learning-nanodegree--nd101) - [Digital Marketing](https://www.udacity.com/course/digital-marketing-nanodegree--nd018) - [Flying Car and Autonomous Flight Engineer](https://www.udacity.com/course/flying-car-nanodegree--nd787) - [Intro to Self-Driving Cars](https://www.udacity.com/course/intro-to-self-driving-cars--nd113) - [Machine Learning Engineer](https://www.udacity.com/course/aws-machine-learning-engineer-nanodegree--nd189) - [Robotics Software Engineer](https://www.udacity.com/course/robotics-software-engineer--nd209) - [![facebook](https://www.udacity.com/blog/wp-content/uploads/2024/07/facebook.svg)](https://www.facebook.com/Udacity) - [![twitter](https://www.udacity.com/blog/wp-content/uploads/2024/07/twitter.svg)](https://twitter.com/udacity) - [![linkedin](https://www.udacity.com/blog/wp-content/uploads/2024/07/linkedin.svg)](https://www.linkedin.com/company/udacity) - [![instagram](https://www.udacity.com/blog/wp-content/uploads/2024/07/instagram.svg)](https://www.instagram.com/udacity/) © 2011–2026 Udacity, Inc. "Nanodegree" is a registered trademark of Udacity. © 2011-2024 Udacity, Inc. We use cookies and other data collection technologies to provide the best experience for our customers. - [Legal & Privacy](https://www.udacity.com/legal) - [Site Map](https://www.udacity.com/sitemap) \[et\_bloom\_locked optin\_id=”optin\_4″\] ### Click below to download your preferred Career Guide [Web Developer Career Guide](https://www.udacity.com/wp-content/uploads/2019/10/Web_Developer_Career_Guide_2019.pdf) [Cloud Career Guide](https://www.udacity.com/wp-content/uploads/2019/10/cloud-career-infographic-2019.pdf) [Data Career Guide](https://www.udacity.com/wp-content/uploads/2019/10/TheCompleteGuidetoLandingaCareerinData_July2018.pdf) [Robotics Career Guide](https://www.udacity.com/wp-content/uploads/2019/10/UdacityRoboticsJobGuide.pdf) \[/et\_bloom\_locked\] ×
Readable Markdown
[Start Learning](https://www.udacity.com/course/c-plus-plus-nanodegree--nd213?utm_source=Blog&utm_medium=Blog&utm_campaign=C%2B%2B%20Strings%20Explained&utm_content=blog) Imagine you’re in line at a lemonade stand on a hot summer day, waiting to reach the front so you can enjoy a refreshing drink. Without having to think about it, you know that the first person to join the line will be the first person to leave it, and the last person to join will be the last to receive a drink. The same concept exists in programming—in [C++](https://www.udacity.com/course/c-plus-plus-nanodegree--nd213), this built-in data structure is called a queue. In this article, we’ll touch on what queues are and how to use them, and we’ll discuss some circumstances in which you might use and avoid queues. ![C++ Queues](https://www.udacity.com/blog/wp-content/uploads/2020/04/AdobeStock_298066277.jpeg) Photo of administrator responsible for cyber security of large corporation searching for safety gaps debugging existant operating system to reduce hacker attacks success probability ## What is a queue in C++? A queue is a data structure that is optimized for a specific access pattern: the “first in, first out” (FIFO) pattern that describes lines as we know them in everyday life. In addition to a garden-variety queue, C++ also has the concept of a priority queue, which you can think of as a structured or organized queue. The top element (largest, greatest, etc.) is always moved to the front of the queue, the bottom element is moved to the back, and each element in between has a priority in relation to all other elements. C++ has built-in queue and priority\_queue data structures. ## How to use a C++ queue The basic operations available to you when working with queues include creating a new queue, adding elements to it and retrieving elements. Let’s look at how this works with both a FIFO queue and a priority queue. ### **FIFO Queues** First, let’s create a queue: ``` #include <iostream> // std::cout #include <queue> // std::queue using namespace std; int main () { queue<int> my_queue; } ``` This creates an empty queue, which we have illustratively named my\_queue. Now, how can we add an element to this queue? Since we initialized our queue to contain integers, let’s add one using the push member function. Keep in mind that we need to do this using the same scope in which we declared our queue: ``` my_queue.push(7); ``` Since our queue is empty, the integer 7 will be the only element. But say we push another element—where will it stand in the queue? The answer is that adding an element assigns it the last index, as the newest member of the queue. As far as retrieving elements goes, the front and back functions will return references to those respective elements in the queue. Let’s push another integer into our queue so that the front and back functions will return different integers. ``` my_queue.push(3); my_queue.front(); // returns 7 my_queue.back(); // returns 3 ``` It’s important to note that while we have operations that retrieve elements from the front and back, we don’t have a way to get an element from the middle of a queue. If we push another integer—say, 4—to our queue, we have no way of accessing 3, now in the middle of our queue. ### **Priority Queues** Now that you’ve grasped the foundations of C++ queues, let’s look at the same operations in priority queues. Creating a priority queue (and then populating it with a for-loop) looks like this: ``` #include <iostream> // std::cout #include <queue> // std::queue using namespace std; int main () { priority_queue<int> my_priority_queue; for (int i = 5; i > 0; --i) my_priority_queue.push(i); // adds 5, 4, 3, 2, 1 } ``` Priority queues have most of the same operations as queues have, with a few additions like top(). The top member function replaces the front member function used for FIFO queues. Note that there is no priority-queue equivalent to the back function. Say we add this line right after our for-loop: ``` cout << my_priority_queue.top() << endl; ``` What do you think this will print out? If you said 5, you are correct. What if we changed the order in which elements were pushed into the priority queue, so that the smallest elements are added first? ``` #include <iostream> // std::cout #include <queue> // std::queue int main () { priority_queue<int> my_priority_queue; for (int i = 0; i < 5; ++i) my_priority_queue.push(i + 1); // adds 1, 2, 3, 4, 5 cout << my_priority_queue.top() << endl; } ``` If this were a FIFO queue, we would expect 1 to be the first item, since it was pushed first. However, the code prints out 5 when we call top(). As expected, our priority queue has ordered the elements for us. To check if this is really how priority queues work, let’s now call pop(), a function (also available in FIFO queues) that removes the topmost element and returns its value. With a priority queue, we should see that the numbers returned by pop are ordered, so let’s try it and see: ``` priority_queue.pop(); // returns 5 priority_queue.pop(); // returns 4 priority_queue.pop(); // returns 3 priority_queue.pop(); // returns 2 priority_queue.pop(); // returns 1 ``` And so we see that this priority queue really is ordered. Now that we have an understanding of both types of queues, let’s move on to some use cases for these data structures. ## When to use queues in C++ Queues are great at keeping track of tasks to process and are the right choice if you need to track the order in which items need to be processed. If, for example, a movie studio has a number of scenes to render on its server farm, a queue will effectively keep track of which task came in first and handles it first. Perhaps you don’t need to keep track of the order elements are inserted, but you do need to order tasks according to a certain metric. In this case queues can still be a great fit—priority queues, that is. Back in our movie studio example, some projects will have a higher priority, and a priority queue will help those get taken care of first. ## When to avoid using queues in C++ As previously noted, we can’t reference queue elements outside of the first and last ones, so if you’re looking for access to, say, the sixth element of a 12-element list, a queue is not the right data structure for you. You might find an array better suited to this purpose. ## Underlying containers in C++ So far we have only touched on the first argument used in FIFO queues and priority queues. As you know, this first argument specifies the type of elements in the queue, but you can also specify an optional second argument. A priority queue is a container adapter, which changes the functionality of a given container type by imposing limitations on it. The optional second argument specifies the underlying container that actually stores the elements. Let’s look at our previous example and add in a second argument: ``` priority_queue<int, vector<int> > my_priority_queue ``` Here, a [vector](https://www.cplusplus.com/reference/vector/vector/vector/) is the underlying container—that is, the priority queue uses a vector container to store its values. It is worthwhile to note that the elements in the underlying container are accessed by the member functions of the container adapter (the priority queue), and not by those of the container (the vector) itself. Remember, the second argument is optional. If none is provided, a FIFO queue defaults to a [deque](https://www.cplusplus.com/reference/deque/deque/) as its container adapter, and a priority queue defaults to a vector. Other underlying container options include a list (for a FIFO queue) and a deque (for a priority queue). ## Further reading and resources This is a [comprehensive overview](https://www.tutorialspoint.com/cpp_standard_library/queue.htm) of member functions available to FIFO queues and priority queues. Here is a [great overview](http://www.cplusplus.com/reference/queue/queue/) [of](http://www.cplusplus.com/reference/queue/queue/) FIFO [queues](http://www.cplusplus.com/reference/queue/queue/) and another for [priority queues](http://www.cplusplus.com/reference/queue/priority_queue/). ## Conclusion In this article, we covered what C++ FIFO queues and priority queues are, and we walked through the code for instantiating, adding to and retrieving from these data structures. We went over some ideal circumstances for using queues and talked about when other data structures might be more appropriate. [Start Learning](https://www.udacity.com/course/c-plus-plus-nanodegree--nd213?utm_source=Blog&utm_medium=Blog&utm_campaign=C%2B%2B%20Strings%20Explained&utm_content=blog)
Shard35 (laksa)
Root Hash694271346773366035
Unparsed URLcom,udacity!www,/blog/2020/03/c-queues-explained.html s443