🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 143 (from laksa042)

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
9 hours ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0 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://careerkarma.com/blog/c-plus-plus-queue/
Last Crawled2026-04-06 16:50:05 (9 hours ago)
First Indexed2020-03-20 23:32:08 (6 years ago)
HTTP Status Code200
Meta TitleHow to Use C++ Queues? Learn with Career Karma.
Meta DescriptionC++ queues are used by developers to create data structures using the first-in, first-out approach. On Career Karma, learn how to work with C++ queues.
Meta Canonicalnull
Boilerpipe Text
How to Use C++ Queues In programming, queues are used to create data structures using the first-in, first-out (FIFO) approach. When you’re programming in C++, you may decide that you want to store a particular set of values in a FIFO structure. For instance, if you’re creating an app that stores a list of orders at a coffee shop, you would want them to be stored in a FIFO order. That’s where the C++ queue comes in. This tutorial will discuss the basics of queues, how to use queues in C++ to store data, and explore the main methods used to work with queues in C++. By the end of this tutorial, you’ll be an expert at using the C++ queue structure. C++ Queues Queues are a type of container adaptor in C++. They are used to implement a first-in, first-out (FIFO) data structure in programming. This structure means that the first item in a queue will be the first one on which an operation is performed. Elements are inserted and stored in the FIFO order. For instance, if you want to remove an item from a queue, the first one to be removed will be the first one in the queue. One example we could use to demonstrate the queue structure would be to think about shopping at a store. The first person who goes in line to check out will be the first one to be served; the second person in the queue will be served next, and so on. To declare a queue in C++, we must use the queue package. This package allows us to use queues in our code. We can use the following code to include the queue package in our code: #include <queue> Now that we’ve imported queue into our code, we can start working with the queue data structure. Declare a Queue in C++ Declaring a queue is another term used to describe the process of creating a queue. So, when you declare a C++ queue, you are telling your program that a queue should be created. Here’s the syntax that is used to declare a queue in C++: queue <dataType> queueName; Let’s break this down. Here are the three main components in our queue: queue instructs our program to create a queue. dataType is the type of data that is to be stored in our queue. queueName is the name of our queue. Suppose we are operating a coffee shop and we are building a program which keeps track of our orders. Our program should use a queue to store the names of customers who have ordered a coffee so our baristas know who to serve in what order. We could use the following code to declare a queue to serve this purpose: queue <string> pendingOrders; In our code, we have declared a queue called pendingOrders . This queue can store string values. Add Item to a C++ Queue C++ queues are used to store data, which means that there are a number of features we can use to manipulate the contents of a queue. The push() method is used to add an item to a C++ queue. push() accepts one parameter, which is the value of the item you want to add to a specified queue. Let’s return to the coffee shop example from earlier to demonstrate the push() method in action. Suppose we have just opened our store and two customers have placed an order: Holly and Jim. Holly was first to place an order, then Jim placed his order. We could use the following code to add Holly and Jim to our queue: #include <iostream> #include <queue> #include <string> int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); return 0; } In this example, we have added Holly and Jim to our queue called pendingOrders in that order. Our code returns 0, which tells us that our code has finished running. Let’s break down our code. First, we import the queue and string libraries which are used to work with the queue data structure and string data type, respectively. We then use the queue method to create a queue called pendingOrders . This queue is capable of storing string values. Next we use the push() method to add Holly’s name to our queue, and we use push() to add Jim’s name to the queue on the next line. This means that Holly is first in our queue, and Jim is second in our queue. Here’s what our queue looks like: Item Holly Jim Remove Item from a C++ Queue The pop() method is used to remove an item from a queue in C++. The pop() function removes the item at the first position in the queues, because queues use the first-in, first-out data structure. Suppose our barista has just processed Holly’s coffee order and wants to remove Holly’s name from the list of pending orders. We could use the following code to accomplish this task: #include <iostream> #include <queue> #include <string> int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); pendingOrders.pop(); return 0; } In this example, we have added Holly and Jim to our queue called pendingOrders . Then we used the pop() method to remove the first item in our queue. Our code returns 0, to indicate that our program has finished running. Here’s what our queue looks like now that we have removed Holly’s name from the queue: "Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!" Venus, Software Engineer at Rockbot Item Jim As you can see, our queue only has one item remaining, which is Jim’s name. Retrieve Item from a C++ Queue The front() and back() methods are used to retrieve the items at the front and the back of a queue in C++. C++ Queue front Suppose our barista wants to know the next order that is pending so they can start working on brewing the customer’s coffee. We could use the following code to find out the name of the next customer whose order is pending: #include <iostream> #include <queue> #include <string> int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); cout << pendingOrders.front() } Our code returns: Holly . In our code, we first declare a queue called pendingOrders and add the names Holly and Jim to the queue (in that order). We then use the front() method to retrieve the item at the front of the queue, and we print it to the console using cout. C++ Queue back Let’s say that our barista wants to know the most recent order placed in our queue. This is the order at the back of the queue, because queues use the first-in, first-out structure. We could use the back() method to retrieve the most recent order placed in the queue: #include <iostream> #include <queue> #include <string> int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); cout << pendingOrders.back() } Our code returns: Jim . In this example, we have initialized a queue and assigned it the values Holly and Jim like we did in our example using the front() method. But instead of using front() to print the first item in our queue, we use back() to print the last item in our queue. Because Jim was added last to our queue, his name was returned by the back() method. Print a C++ Queue When you’re working with queues in C++, you may decide that you want to print the contents of a queue to the console. C++ does not include any specific method that is used to print a queue to the console, but we can use a while loop to print out the contents of a queue. For instance, suppose we wanted to print out a list of our pending orders at the coffee shop so that our baristas know who to serve in what order. We could use the following code to accomplish this goal: #include <iostream> #include <queue> #include <string> include namespace std; void showQueue(queue <string> pendingOrders) { queue <string> orders = pendingOrders; while (!orders.empty()) { cout << "\t" << orders.front(); orders.pop(); } cout << "\n"; } int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); showQueue(pendingOrders); } Our code returns: Holly Jim Let’s break down our code. In our example, we have declared a function called showQueue which accepts a queue called pendingOrders as a parameter. This function creates a new queue called orders, then uses a while loop to print out every item in the queue. The while loop uses the empty() method to check if the orders queue is empty. !empty() means that the while loop should run until the orders queue is empty. The while loop in our code executes the following steps: A new tab character ( \t ) is printed to the console, followed by the first item in the orders queue. This item is accessed using the front() method. The first item in the orders queue is removed using pop() . This allows our while loop to retrieve the contents of the next item in our queue on its next iteration. In our main program, we first create a queue called pendingOrders , then we add Holly and Jim to our queue. Finally, we invoke the showQueue() method which prints out the contents of the pendingOrders queue that we specified as a parameter to showQueue() . Other Queue Methods There are four additional C++ queue methods that you may want to use in your code. Here is a reference table with a brief description of each of these methods: Method Description size() Returns the size of the queue. emplace() Inserts new elements in the queue above the last element in the queue. swap() Swaps the contents of two containers. empty() Checks whether a queue is empty. Returns true if a queue is empty, and false if a queue contains one or more values. Conclusion The queue structure is used in C++ to create queues. Queues leverage the first-in, first-out data structure, which means the first item in the queue is the first one which will leave the queue when an item is removed. This tutorial discussed, with references to examples, the basics of queues in C++, and how to perform common operations on a C++ queue such as adding and removing array items using push and pop. Now you’re ready to start working with C++ queues like an expert developer!
Markdown
![](https://www.facebook.com/tr?id=726791754150577&ev=PageView&noscript=1) Not sure which program is right for you? Talk to our AI Career Advisor now [Start a conversation](https://careerkarma.app/?utm_source=ck-blog&utm_medium=embed&utm_campaign=sitewide&utm_content=top-banner) X Back Bootcamps - [Graduate Stories](https://careerkarma.com/blog/stories/) - [Partner Spotlights](https://careerkarma.com/blog/partner-spotlight/) - [Bootcamp Prep](https://careerkarma.com/blog/bootcamp-prep/) - [Bootcamp Admissions](https://careerkarma.com/blog/bootcamp-admissions/) - [University Bootcamps](https://careerkarma.com/blog/university-bootcamps/) - [Research](https://careerkarma.com/blog/research/) Coding - [Python](https://careerkarma.com/blog/python/) - [Git](https://careerkarma.com/blog/git/) - [JavaScript](https://careerkarma.com/blog/javascript/) - [CSS](https://careerkarma.com/blog/css/) - [Java](https://careerkarma.com/blog/java/) - [HTML](https://careerkarma.com/blog/html/) - [C++](https://careerkarma.com/blog/c-plus-plus/) - [SQL](https://careerkarma.com/blog/sql/) - [Ruby](https://careerkarma.com/blog/ruby/) - [Coding Tools](https://careerkarma.com/blog/coding-tools/) Tech Skills - [Software Engineering](https://careerkarma.com/blog/software-engineering-skills) - [Web Development](https://careerkarma.com/blog/web-development-skills) - [Data Science](https://careerkarma.com/blog/data-science-skills/) - [Design](https://careerkarma.com/blog/design-skills/) - [Tech Guides](https://careerkarma.com/blog/tech-guides/) - [Tech Resources](https://careerkarma.com/blog/tech-resources/) - [Tech Tools](https://careerkarma.com/blog/tech-tools/) Career Resources - [Career Advice](https://careerkarma.com/blog/career-advice/) - [Online Learning](https://careerkarma.com/blog/online-learning/) - [Resume](https://careerkarma.com/blog/resume/) - [Interviews](https://careerkarma.com/blog/interviews/) - [Tech Jobs](https://careerkarma.com/blog/tech-jobs/) - [Internships](https://careerkarma.com/blog/internships/) - [Apprenticeships](https://careerkarma.com/blog/apprenticeships/) - [Tech Salaries](https://careerkarma.com/blog/tech-salaries/) - [Job Market](https://careerkarma.com/blog/job-market/) [Trade School](https://careerkarma.com/blog/trades/) Higher Ed - [Degrees](https://careerkarma.com/blog/degrees/) - [Associate Degree](https://careerkarma.com/blog/associate/) - [Bachelor's Degree](https://careerkarma.com/blog/bachelors/) - [Master's Degree](https://careerkarma.com/blog/masters/) - [Doctoral](https://careerkarma.com/blog/doctoral/) - [University Admissions](https://careerkarma.com/blog/university-admissions/) - [Best Schools](https://careerkarma.com/blog/best-schools/) - [Certifications](https://careerkarma.com/blog/certifications/) Ed Financing - [Bootcamp Financing](https://careerkarma.com/blog/bootcamp-financing/) - [Higher Ed Financing](https://careerkarma.com/blog/higher-ed-financing/) - [Scholarships](https://careerkarma.com/blog/scholarships/) - [Financial Aid](https://careerkarma.com/blog/financial-aid/) Global navigation Browse Bootcamps - Popular Bootcamps - [Artificial Intelligence](https://careerkarma.com/subjects/best-artificial-intelligence-bootcamps) - [Coding](https://careerkarma.com/rankings/best-coding-bootcamps/) - [Cybersecurity](https://careerkarma.com/rankings/best-cyber-security-bootcamps/) - [Data Analytics](https://careerkarma.com/rankings/best-data-analytics-bootcamps/) - [Data Science](https://careerkarma.com/rankings/best-data-science-bootcamps/) - [Design](https://careerkarma.com/rankings/best-web-design-bootcamps/) - [Digital Marketing](https://careerkarma.com/rankings/best-digital-marketing-bootcamps/) - [QA/Testing](https://careerkarma.com/subjects/best-artificial-intelligence-bootcamps) - [Software Engineering](https://careerkarma.com/rankings/best-online-bootcamps/) - [Explore other popular bootcamps](https://careerkarma.com/rankings) - Bootcamps Near You - [Atlanta](https://careerkarma.com/locations/atlanta/) - [Boston](https://careerkarma.com/locations/boston/) - [Chicago](https://careerkarma.com/locations/chicago/) - [Houston](https://careerkarma.com/locations/houston/) - [Los Angeles](https://careerkarma.com/locations/los-angeles/) - [New York City](https://careerkarma.com/locations/new-york/) - [San Francisco](https://careerkarma.com/locations/san-francisco/) - [Seattle](https://careerkarma.com/locations/seattle/) - [View more locations](https://careerkarma.com/locations) - Explore by Subject - [Back End Development](https://careerkarma.com/subjects/best-back-end-bootcamps) - [JavaScript](https://careerkarma.com/subjects/best-javascript-bootcamps/) - [Machine Learning](https://careerkarma.com/subjects/best-machine-learning-bootcamps/) - [Penetration Testing](https://careerkarma.com/subjects/best-penetration-testing-bootcamps) - [Python](https://careerkarma.com/subjects/best-python-bootcamps/) - [React](https://careerkarma.com/subjects/best-react-bootcamps) - [SQL](https://careerkarma.com/subjects/best-sql-bootcamps/) - [View more subjects](https://careerkarma.com/subjects/) Trade Schools - Get Career Advice - [CDL](https://careerkarma.com/blog/trades-cdl) - [HVAC](https://careerkarma.com/blog/trades-hvac) - Match with Programs - [CDL](https://careerkarma.com/fasttrack/cdl) - [HVAC](https://careerkarma.com/fasttrack/hvac) - Programs Near You - [CDL](https://careerkarma.com/blog/browse-cdl-programs) - [HVAC](https://careerkarma.com/blog/browse-hvac-programs) Learn for Free - Browse Questions From Others - [Bootcamps 101](https://careerkarma.com/discussions/tags/beginners/) - [Data Science](https://careerkarma.com/discussions/tags/data-science/) - [Software Engineering](https://careerkarma.com/discussions/tags/software-engineering/) - [Full-Stack Development](https://careerkarma.com/discussions/tags/full-stack-development/) - [JavaScript](https://careerkarma.com/discussions/tags/javascript/) - [Job Search](https://careerkarma.com/discussions/tags/job-search/) - [Career Changes](https://careerkarma.com/discussions/tags/jobs/) - [View all Career Discussions](https://careerkarma.com/discussions/) - Browse Top Careers - [Software Engineering](https://careerkarma.com/careers/software-engineer/) - [Web Development](https://careerkarma.com/careers/web-developer/) - [Mobile App Development](https://careerkarma.com/careers/mobile-development/) - [Data Science](https://careerkarma.com/careers/data-science/) - [Cybersecurity](https://careerkarma.com/careers/cybersecurity/) - [Product Management](https://careerkarma.com/careers/product-management/) - [Digital Marketing](https://careerkarma.com/careers/digital-marketing/) - [UX/UI Design](https://careerkarma.com/careers/design/) - Choosing a Bootcamp - [What is a Coding Bootcamp?](https://careerkarma.com/blog/what-is-a-coding-bootcamp/) - [Are Coding Bootcamps Worth It?](https://careerkarma.com/blog/are-coding-bootcamps-worth-it/) - [How to Choose a Coding Bootcamp](https://careerkarma.com/blog/how-to-choose-a-coding-bootcamp/) - [Best Online Coding Bootcamps and Courses](https://careerkarma.com/blog/best-online-coding-bootcamps/) - [Best Free Bootcamps and Coding Training](https://careerkarma.com/blog/best-free-coding-bootcamps/) - [Coding Bootcamp vs. Community College](https://careerkarma.com/blog/coding-bootcamp-vs-degree/) - [Coding Bootcamp vs. Self-Learning](https://careerkarma.com/blog/coding-bootcamp-versus-self-study/) - [Bootcamps vs. Certifications: Compared](https://careerkarma.com/blog/bootcamps-vs-certifications/) - [What Is a Coding Bootcamp Job Guarantee?](https://careerkarma.com/blog/coding-bootcamp-job-guarantee/) - Paying for a Bootcamp - [How to Pay for Coding Bootcamp](https://careerkarma.com/blog/how-to-pay-for-coding-bootcamp/) - [Ultimate Guide to Coding Bootcamp Loans](https://careerkarma.com/blog/coding-bootcamp-loans/) - [Best Coding Bootcamp Scholarships and Grants](https://careerkarma.com/blog/coding-bootcamp-scholarships/) - [Education Stipends for Coding Bootcamps](https://careerkarma.com/blog/coding-bootcamp-with-living-stipend/) - [Get Your Coding Bootcamp Sponsored by Your Employer](https://careerkarma.com/blog/coding-bootcamp-employer-sponsorship/) - [GI Bill and Coding Bootcamps](https://careerkarma.com/blog/gi-bill-coding-bootcamps/) - Other Topics in Tech - [Tech Intevriews](https://careerkarma.com/blog/interviews/) - [Career Advice](https://careerkarma.com/blog/career-advice/) - [Python](https://careerkarma.com/blog/python/) - [HTML](https://careerkarma.com/blog/html/) - [CSS](https://careerkarma.com/blog/css/) - [JavaScript](https://careerkarma.com/blog/javascript/) - [Git](https://careerkarma.com/blog/git/) - [Java](https://careerkarma.com/blog/java/) - [C++](https://careerkarma.com/blog/c-plus-plus/) About - [Company](https://careerkarma.com/about/) - [Jobs](https://careerkarma.com/company/jobs/) - [Values](https://careerkarma.com/company/values/) - [Publication](https://careerkarma.com/blog/about/) - [Press](https://careerkarma.com/company/press/) - [Partner With Us](https://form.typeform.com/to/f9954oum) - [Stories](https://careerkarma.com/blog/stories/) [Privacy Policy](https://privacy.careerkarma.com/privacy-policy) [Terms of Use](https://careerkarma.com/terms-of-use/) [Do not sell my personal info](https://privacy.careerkarma.com/opt-out) © 2026 Career Karma [![Career Karma](https://careerkarma.com/blog/wp-content/uploads/2023/07/logo-circle-60x60.png)](https://careerkarma.com/) [![Career Karma](https://careerkarma.com/blog/wp-content/uploads/2024/02/ck_logo.png)](https://careerkarma.com/) [Sign In](https://careerkarma.com/sign-in) Get Matched - [Browse Bootcamps](https://careerkarma.com/) - [Popular Bootcamps](https://careerkarma.com/) - [Artificial Intelligence](https://careerkarma.com/subjects/best-artificial-intelligence-bootcamps) - [Coding](https://careerkarma.com/rankings/best-coding-bootcamps/) - [Cybersecurity](https://careerkarma.com/rankings/best-cyber-security-bootcamps/) - [Data Analytics](https://careerkarma.com/rankings/best-data-analytics-bootcamps/) - [Data Science](https://careerkarma.com/rankings/best-data-science-bootcamps/) - [Design](https://careerkarma.com/rankings/best-web-design-bootcamps/) - [Digital Marketing](https://careerkarma.com/rankings/best-digital-marketing-bootcamps/) - [QA/Testing](https://careerkarma.com/subjects/best-artificial-intelligence-bootcamps) - [Software Engineering](https://careerkarma.com/rankings/best-online-bootcamps/) - [Explore other popular bootcamps](https://careerkarma.com/rankings) - [Bootcamps Near You](https://careerkarma.com/) - [Atlanta](https://careerkarma.com/locations/atlanta/) - [Boston](https://careerkarma.com/locations/boston/) - [Chicago](https://careerkarma.com/locations/chicago/) - [Houston](https://careerkarma.com/locations/houston/) - [Los Angeles](https://careerkarma.com/locations/los-angeles/) - [New York City](https://careerkarma.com/locations/new-york/) - [San Francisco](https://careerkarma.com/locations/san-francisco/) - [Seattle](https://careerkarma.com/locations/seattle/) - [View more locations](https://careerkarma.com/locations) - [Explore by Subject](https://careerkarma.com/) - [Back End Development](https://careerkarma.com/subjects/best-back-end-bootcamps) - [JavaScript](https://careerkarma.com/subjects/best-javascript-bootcamps/) - [Machine Learning](https://careerkarma.com/subjects/best-machine-learning-bootcamps/) - [Penetration Testing](https://careerkarma.com/subjects/best-penetration-testing-bootcamps) - [Python](https://careerkarma.com/subjects/best-python-bootcamps/) - [React](https://careerkarma.com/subjects/best-react-bootcamps) - [SQL](https://careerkarma.com/subjects/best-sql-bootcamps/) - [View more subjects](https://careerkarma.com/subjects/) - [Trade Schools](https://careerkarma.com/) - [Get Career Advice](https://careerkarma.com/) - [CDL](https://careerkarma.com/blog/trades-cdl) - [HVAC](https://careerkarma.com/blog/trades-hvac) - [Match with Programs](https://careerkarma.com/) - [CDL](https://careerkarma.com/fasttrack/cdl) - [HVAC](https://careerkarma.com/fasttrack/hvac) - [Programs Near You](https://careerkarma.com/) - [CDL](https://careerkarma.com/blog/browse-cdl-programs) - [HVAC](https://careerkarma.com/blog/browse-hvac-programs) - [Learn for Free](https://careerkarma.com/) - [Browse Questions From Others](https://careerkarma.com/) - [Bootcamps 101](https://careerkarma.com/discussions/tags/beginners/) - [Data Science](https://careerkarma.com/discussions/tags/data-science/) - [Software Engineering](https://careerkarma.com/discussions/tags/software-engineering/) - [Full-Stack Development](https://careerkarma.com/discussions/tags/full-stack-development/) - [JavaScript](https://careerkarma.com/discussions/tags/javascript/) - [Job Search](https://careerkarma.com/discussions/tags/job-search/) - [Career Changes](https://careerkarma.com/discussions/tags/jobs/) - [View all Career Discussions](https://careerkarma.com/discussions/) - [Browse Top Careers](https://careerkarma.com/) - [Software Engineering](https://careerkarma.com/careers/software-engineer/) - [Web Development](https://careerkarma.com/careers/web-developer/) - [Mobile App Development](https://careerkarma.com/careers/mobile-development/) - [Data Science](https://careerkarma.com/careers/data-science/) - [Cybersecurity](https://careerkarma.com/careers/cybersecurity/) - [Product Management](https://careerkarma.com/careers/product-management/) - [Digital Marketing](https://careerkarma.com/careers/digital-marketing/) - [UX/UI Design](https://careerkarma.com/careers/design/) - [Choosing a Bootcamp](https://careerkarma.com/blog/) - [What is a Coding Bootcamp?](https://careerkarma.com/blog/what-is-a-coding-bootcamp/) - [Are Coding Bootcamps Worth It?](https://careerkarma.com/blog/are-coding-bootcamps-worth-it/) - [How to Choose a Coding Bootcamp](https://careerkarma.com/blog/how-to-choose-a-coding-bootcamp/) - [Best Online Coding Bootcamps and Courses](https://careerkarma.com/blog/best-online-coding-bootcamps/) - [Best Free Bootcamps and Coding Training](https://careerkarma.com/blog/best-free-coding-bootcamps/) - [Coding Bootcamp vs. Community College](https://careerkarma.com/blog/coding-bootcamp-vs-degree/) - [Coding Bootcamp vs. Self-Learning](https://careerkarma.com/blog/coding-bootcamp-versus-self-study/) - [Bootcamps vs. Certifications: Compared](https://careerkarma.com/blog/bootcamps-vs-certifications/) - [What Is a Coding Bootcamp Job Guarantee?](https://careerkarma.com/blog/coding-bootcamp-job-guarantee/) - [Paying for a Bootcamp](https://careerkarma.com/blog/) - [How to Pay for Coding Bootcamp](https://careerkarma.com/blog/how-to-pay-for-coding-bootcamp/) - [Ultimate Guide to Coding Bootcamp Loans](https://careerkarma.com/blog/coding-bootcamp-loans/) - [Best Coding Bootcamp Scholarships and Grants](https://careerkarma.com/blog/coding-bootcamp-scholarships/) - [Education Stipends for Coding Bootcamps](https://careerkarma.com/blog/coding-bootcamp-with-living-stipend/) - [Get Your Coding Bootcamp Sponsored by Your Employer](https://careerkarma.com/blog/coding-bootcamp-employer-sponsorship/) - [GI Bill and Coding Bootcamps](https://careerkarma.com/blog/gi-bill-coding-bootcamps/) - [Other Topics in Tech](https://careerkarma.com/blog/) - [Tech Intevriews](https://careerkarma.com/blog/interviews/) - [Career Advice](https://careerkarma.com/blog/career-advice/) - [Python](https://careerkarma.com/blog/python/) - [HTML](https://careerkarma.com/blog/html/) - [CSS](https://careerkarma.com/blog/css/) - [JavaScript](https://careerkarma.com/blog/javascript/) - [Git](https://careerkarma.com/blog/git/) - [Java](https://careerkarma.com/blog/java/) - [C++](https://careerkarma.com/blog/c-plus-plus/) - [About](https://careerkarma.com/) - [Company](https://careerkarma.com/about/) - [Jobs](https://careerkarma.com/company/jobs/) - [Values](https://careerkarma.com/company/values/) - [Publication](https://careerkarma.com/blog/about/) - [Press](https://careerkarma.com/company/press/) - [Partner With Us](https://form.typeform.com/to/f9954oum) - [Stories](https://careerkarma.com/blog/stories/) - [Sign In](https://careerkarma.com/sign-in/) - [Get Matched](https://careerkarma.com/fasttrack/?from=navigationbar) - [Resource Center](https://careerkarma.com/blog/) - [Bootcamps](https://careerkarma.com/blog/bootcamp/) - [Graduate Stories](https://careerkarma.com/blog/stories/) - [Partner Spotlights](https://careerkarma.com/blog/partner-spotlight/) - [Bootcamp Prep](https://careerkarma.com/blog/bootcamp-prep/) - [Bootcamp Admissions](https://careerkarma.com/blog/bootcamp-admissions/) - [University Bootcamps](https://careerkarma.com/blog/university-bootcamps/) - [Research](https://careerkarma.com/blog/research/) - [Coding](https://careerkarma.com/blog/learn-coding/) - [Python](https://careerkarma.com/blog/python/) - [Git](https://careerkarma.com/blog/git/) - [JavaScript](https://careerkarma.com/blog/javascript/) - [CSS](https://careerkarma.com/blog/css/) - [Java](https://careerkarma.com/blog/java/) - [HTML](https://careerkarma.com/blog/html/) - [C++](https://careerkarma.com/blog/c-plus-plus/) - [SQL](https://careerkarma.com/blog/sql/) - [Ruby](https://careerkarma.com/blog/ruby/) - [Coding Tools](https://careerkarma.com/blog/coding-tools/) - [Tech Skills](https://careerkarma.com/blog/tech-skills/) - [Software Engineering](https://careerkarma.com/blog/software-engineering-skills) - [Web Development](https://careerkarma.com/blog/web-development-skills) - [Data Science](https://careerkarma.com/blog/data-science-skills/) - [Design](https://careerkarma.com/blog/design-skills/) - [Tech Guides](https://careerkarma.com/blog/tech-guides/) - [Tech Resources](https://careerkarma.com/blog/tech-resources/) - [Tech Tools](https://careerkarma.com/blog/tech-tools/) - [Career Resources](https://careerkarma.com/blog/career-resource/) - [Career Advice](https://careerkarma.com/blog/career-advice/) - [Online Learning](https://careerkarma.com/blog/online-learning/) - [Resume](https://careerkarma.com/blog/resume/) - [Interviews](https://careerkarma.com/blog/interviews/) - [Tech Jobs](https://careerkarma.com/blog/tech-jobs/) - [Internships](https://careerkarma.com/blog/internships/) - [Apprenticeships](https://careerkarma.com/blog/apprenticeships/) - [Tech Salaries](https://careerkarma.com/blog/tech-salaries/) - [Job Market](https://careerkarma.com/blog/job-market/) - [Trade School](https://careerkarma.com/blog/trades/) - [Higher Ed](https://careerkarma.com/blog/higher-ed/) - [Degrees](https://careerkarma.com/blog/degrees/) - [Associate Degree](https://careerkarma.com/blog/associate/) - [Bachelor’s Degree](https://careerkarma.com/blog/bachelors/) - [Master’s Degree](https://careerkarma.com/blog/masters/) - [Doctoral](https://careerkarma.com/blog/doctoral/) - [University Admissions](https://careerkarma.com/blog/university-admissions/) - [Best Schools](https://careerkarma.com/blog/best-schools/) - [Certifications](https://careerkarma.com/blog/certifications/) - [Ed Financing](https://careerkarma.com/blog/ed-financing/) - [Bootcamp Financing](https://careerkarma.com/blog/bootcamp-financing/) - [Higher Ed Financing](https://careerkarma.com/blog/higher-ed-financing/) - [Scholarships](https://careerkarma.com/blog/scholarships/) - [Financial Aid](https://careerkarma.com/blog/financial-aid/) - [About](https://careerkarma.com/blog/about/) - [Resource Center](https://careerkarma.com/blog/) - [Posts](https://careerkarma.com/blog) - [C++ Programming](https://careerkarma.com/blog/c-plus-plus/) - C++ Queue # C++ Queue ## By ![James Gallagher](https://careerkarma.com/blog/wp-content/uploads/2020/01/james-gallagher-150x150.jpg) **[James Gallagher](https://careerkarma.com/blog/author/jamesgallagher/ "Posts by James Gallagher")** Updated December 1, 2023 ## How to Use C++ Queues In programming, queues are used to create data structures using the first-in, first-out (FIFO) approach. When you’re programming in C++, you may decide that you want to store a particular set of values in a FIFO structure. For instance, if you’re creating an app that stores a list of orders at a coffee shop, you would want them to be stored in a FIFO order. Find your bootcamp match Select Your Interest Your experience Time to start GET MATCHED By completing and submitting this form, you agree that Career Karma Platform, LLC may deliver or cause to be delivered information, advertisements, and telemarketing messages regarding their services by email, call, text, recording, and message using a telephone system, dialer, automated technology or system, artificial or prerecorded voice or message device to your email and/or telephone number(s) (and not any other person’s email or telephone number) that you entered. Consent is not a condition of receiving information, receiving Career Karma services, or using the website, and you may obtain information by emailing [info@careerkarma.com](mailto:info@careerkarma.com). Message & Data rates may apply. Message frequency may vary. Text STOP to unsubscribe. [Terms of Service](https://careerkarma.com/terms-of-use) and [Privacy Policy](https://privacy.careerkarma.com/privacy-policy) govern the processing and handling of your data. X By completing and submitting this form, you agree that Career Karma Platform, LLC may deliver or cause to be delivered information, advertisements, and telemarketing messages regarding their services by email, call, text, recording, and message using a telephone system, dialer, automated technology or system, artificial or prerecorded voice or message device to your email and/or telephone number(s) (and not any other person’s email or telephone number) that you entered. Consent is not a condition of receiving information, receiving Career Karma services, or using the website, and you may obtain information by emailing [info@careerkarma.com](mailto:info@careerkarma.com). Message & Data rates may apply. Message frequency may vary. Text STOP to unsubscribe. [Terms of Service](https://careerkarma.com/terms-of-use) and [Privacy Policy](https://privacy.careerkarma.com/privacy-policy) govern the processing and handling of your data. That’s where the C++ queue comes in. This tutorial will discuss the basics of queues, how to use queues in C++ to store data, and explore the main methods used to work with queues in C++. By the end of this tutorial, you’ll be an expert at using the C++ queue structure. ## C++ Queues Queues are a type of container adaptor in C++. They are used to implement a first-in, first-out (FIFO) data structure in programming. This structure means that the first item in a queue will be the first one on which an operation is performed. Elements are inserted and stored in the FIFO order. For instance, if you want to remove an item from a queue, the first one to be removed will be the first one in the queue. One example we could use to demonstrate the queue structure would be to think about shopping at a store. The first person who goes in line to check out will be the first one to be served; the second person in the queue will be served next, and so on. To declare a queue in C++, we must use the queue package. This package allows us to use queues in our code. We can use the following code to include the queue package in our code: ``` #include <queue> ``` Now that we’ve imported queue into our code, we can start working with the queue data structure. ## Declare a Queue in C++ Declaring a queue is another term used to describe the process of creating a queue. So, when you declare a C++ queue, you are telling your program that a queue should be created. Here’s the syntax that is used to declare a queue in C++: ``` queue <dataType> queueName; ``` Let’s break this down. Here are the three main components in our queue: - **queue** instructs our program to create a queue. - **dataType** is the type of data that is to be stored in our queue. - **queueName** is the name of our queue. Suppose we are operating a coffee shop and we are building a program which keeps track of our orders. Our program should use a queue to store the names of customers who have ordered a coffee so our baristas know who to serve in what order. We could use the following code to declare a queue to serve this purpose: ``` queue <string> pendingOrders; ``` In our code, we have declared a queue called `pendingOrders`. This queue can store string values. ## Add Item to a C++ Queue C++ queues are used to store data, which means that there are a number of features we can use to manipulate the contents of a queue. The `push()` method is used to add an item to a C++ queue. `push()` accepts one parameter, which is the value of the item you want to add to a specified queue. Let’s return to the coffee shop example from earlier to demonstrate the `push()` method in action. Suppose we have just opened our store and two customers have placed an order: Holly and Jim. Holly was first to place an order, then Jim placed his order. We could use the following code to add Holly and Jim to our queue: ``` #include <iostream> #include <queue> #include <string> int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); return 0; } ``` In this example, we have added Holly and Jim to our queue called `pendingOrders` in that order. Our code returns 0, which tells us that our code has finished running. Let’s break down our code. First, we import the queue and string libraries which are used to work with the queue data structure and string data type, respectively. We then use the queue method to create a queue called `pendingOrders`. This queue is capable of storing string values. Next we use the `push()` method to add Holly’s name to our queue, and we use `push()` to add Jim’s name to the queue on the next line. This means that Holly is first in our queue, and Jim is second in our queue. Here’s what our queue looks like: | | |---| | **Item** | | Holly | | Jim | ## Remove Item from a C++ Queue The `pop()` method is used to remove an item from a queue in C++. The pop() function removes the item at the first position in the queues, because queues use the first-in, first-out data structure. Suppose our barista has just processed Holly’s coffee order and wants to remove Holly’s name from the list of pending orders. We could use the following code to accomplish this task: ``` #include <iostream> #include <queue> #include <string> int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); pendingOrders.pop(); return 0; } ``` In this example, we have added Holly and Jim to our queue called `pendingOrders`. Then we used the `pop()` method to remove the first item in our queue. Our code returns 0, to indicate that our program has finished running. Here’s what our queue looks like now that we have removed Holly’s name from the queue: ![Venus profile photo](https://careerkarma.com/blog/wp-content/uploads/2024/02/venus.webp) "Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!" Venus, Software Engineer at Rockbot Find Your Bootcamp Match | | |---| | **Item** | | Jim | As you can see, our queue only has one item remaining, which is Jim’s name. ## Retrieve Item from a C++ Queue The `front()` and `back()` methods are used to retrieve the items at the front and the back of a queue in C++. ### C++ Queue front Suppose our barista wants to know the next order that is pending so they can start working on brewing the customer’s coffee. We could use the following code to find out the name of the next customer whose order is pending: ``` #include <iostream> #include <queue> #include <string> int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); cout << pendingOrders.front() } ``` Our code returns: `Holly`. In our code, we first declare a queue called `pendingOrders` and add the names Holly and Jim to the queue (in that order). We then use the `front()` method to retrieve the item at the front of the queue, and we print it to the console using cout. ### C++ Queue back Let’s say that our barista wants to know the most recent order placed in our queue. This is the order at the back of the queue, because queues use the first-in, first-out structure. We could use the `back()` method to retrieve the most recent order placed in the queue: ``` #include <iostream> #include <queue> #include <string> int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); cout << pendingOrders.back() } ``` Our code returns: `Jim`. In this example, we have initialized a queue and assigned it the values Holly and Jim like we did in our example using the `front()` method. But instead of using `front()` to print the first item in our queue, we use `back()` to print the last item in our queue. Because Jim was added last to our queue, his name was returned by the `back()` method. ## Print a C++ Queue When you’re working with queues in C++, you may decide that you want to print the contents of a queue to the console. C++ does not include any specific method that is used to print a queue to the console, but we can use a while loop to print out the contents of a queue. For instance, suppose we wanted to print out a list of our pending orders at the coffee shop so that our baristas know who to serve in what order. We could use the following code to accomplish this goal: ``` #include <iostream> #include <queue> #include <string> include namespace std; void showQueue(queue <string> pendingOrders) { queue <string> orders = pendingOrders; while (!orders.empty()) { cout << "\t" << orders.front(); orders.pop(); } cout << "\n"; } int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); showQueue(pendingOrders); } ``` Our code returns: ``` Holly Jim ``` Let’s break down our code. In our example, we have declared a function called showQueue which accepts a queue called `pendingOrders` as a parameter. This function creates a new queue called orders, then uses a while loop to print out every item in the queue. The while loop uses the `empty()` method to check if the orders queue is empty. `!empty()` means that the while loop should run until the orders queue is empty. The while loop in our code executes the following steps: 1. A new tab character (`\t`) is printed to the console, followed by the first item in the orders queue. This item is accessed using the `front()` method. 2. The first item in the orders queue is removed using `pop()`. This allows our while loop to retrieve the contents of the next item in our queue on its next iteration. In our main program, we first create a queue called `pendingOrders`, then we add Holly and Jim to our queue. Finally, we invoke the `showQueue()` method which prints out the contents of the `pendingOrders` queue that we specified as a parameter to `showQueue()`. ## Other Queue Methods There are four additional C++ queue methods that you may want to use in your code. Here is a reference table with a brief description of each of these methods: | | | |---|---| | **Method** | **Description** | | size() | Returns the size of the queue. | | emplace() | Inserts new elements in the queue above the last element in the queue. | | swap() | Swaps the contents of two containers. | | empty() | Checks whether a queue is empty. Returns true if a queue is empty, and false if a queue contains one or more values. | ## ## Conclusion The queue structure is used in C++ to create queues. Queues leverage the first-in, first-out data structure, which means the first item in the queue is the first one which will leave the queue when an item is removed. This tutorial discussed, with references to examples, the basics of queues in C++, and how to perform common operations on a C++ queue such as adding and removing array items using push and pop. Now you’re ready to start working with C++ queues like an expert developer\! **About us:** Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. [Learn about the CK publication](https://careerkarma.com/blog/about/). #### What's Next? [![icon\_10](https://careerkarma.com/blog/wp-content/uploads/2020/05/get-matched-icon.png) Want to take action? **Get matched** with top bootcamps](https://careerkarma.com/blog/c-plus-plus-queue/) [![icon\_11](https://careerkarma.com/blog/c-plus-plus-queue/%0D%0Ahttps://careerkarma.com/blog/wp-content/uploads/2020/05/ask-icon.png) Want to dive deeper? **Ask** a question to our community](https://careerkarma.com/blog/c-plus-plus-queue/%0D%0Ahttps://careerkarma.com/?utm_campaign=ck-blog&utm_source=whatsnext) [![icon\_12](https://careerkarma.com/blog/c-plus-plus-queue/%0D%0Ahttps://careerkarma.com/blog/wp-content/uploads/2020/05/explore-icon-1.png) Want to explore tech careers? **Take** our careers quiz](https://careerkarma.com/blog/c-plus-plus-queue/%0D%0Ahttps://careerkarma.com/quiz?utm_campaign=ck-blog&utm_source=whatsnext) [![James Gallagher](https://careerkarma.com/blog/wp-content/uploads/2020/01/james-gallagher-300x300.jpg)](https://careerkarma.com/blog/c-plus-plus-queue/) About the Author ![James Gallagher](https://careerkarma.com/blog/wp-content/uploads/2020/01/james-gallagher-150x150.jpg) [James Gallagher](https://careerkarma.com/blog/author/jamesgallagher/) Technical Content Manager at [Career Karma](https://careerkarma.com/) James Gallagher is a self-taught programmer and the technical content manager at Career Karma. He has experience in range of programming languages and extensive expertise in Python, HTML, CSS, and JavaScript. James has written hundreds of programming tuto... [read more about the author](https://careerkarma.com/blog/author/jamesgallagher/) Share This Mar 20, 2020 [Comments (0)]() ### Leave a Reply [Cancel reply](https://careerkarma.com/blog/c-plus-plus-queue/#respond) [![Apply to top tech training programs in one click](https://careerkarma.com/blog/wp-content/uploads/2022/08/sidebar-bootcamp-img.webp)](https://careerkarma.com/fasttrack/?from=sidebar) Apply to top tech training programs in one click [Get Matched](https://careerkarma.com/fasttrack/?from=sidebar) [![logo](https://careerkarma.com/blog/wp-content/uploads/2024/02/ck_logo.png)](https://careerkarma.com/) [Home](https://careerkarma.com/) [About](https://careerkarma.com/blog/about/) [Jobs](https://careerkarma.com/company/jobs/) [Mission](https://careerkarma.com/company/values/) [Resource Center](https://careerkarma.com/blog/) [Press](https://careerkarma.com/company/press/) [Terms & Сonditions](https://careerkarma.com/terms-of-use/) [Sitemap](https://careerkarma.com/blog/html-sitemap/) [Accessibility Statement](https://careerkarma.com/accessibility-statement/) [Facebook](https://www.facebook.com/CareerKarmaApp) [Twitter](https://twitter.com/Career_Karma) [Instagram](https://www.instagram.com/careerkarma) [Youtube](https://www.youtube.com/careerkarma?sub_confirmation=1) © 2025 Career Karma Careers [Cloud Engineer](https://careerkarma.com/careers/cloud-engineer/) [Customer Success Manager](https://careerkarma.com/careers/customer-success-manager/) [Data Analytics](https://careerkarma.com/careers/data-analytics/) [Data Science](https://careerkarma.com/careers/data-science/) [Interaction Designer](https://careerkarma.com/careers/interaction-designer/) [Machine Learning Engineer](https://careerkarma.com/careers/machine-learning/) [Network Engineer](https://careerkarma.com/careers/network-engineer/) [Quality Assurance Engineer](https://careerkarma.com/careers/quality-assurance-engineer/) [Software Engineer](https://careerkarma.com/careers/software-engineer/) [Tech Sales Representative](https://careerkarma.com/careers/tech-sales-representative/) [View More Career Paths](https://careerkarma.com/careers/) Schools [TripleTen](https://careerkarma.com/schools/tripleten/) [Coding Temple](https://careerkarma.com/schools/coding-temple/) [Flatiron School](https://careerkarma.com/schools/flatiron-school/) [Springboard](https://careerkarma.com/schools/springboard/) [Brainstation](https://careerkarma.com/schools/brainstation/) [SheCodes](https://careerkarma.com/schools/shecodes/) [Code Platoon](https://careerkarma.com/schools/code-platoon/) [Tech Elevator](https://careerkarma.com/schools/tech-elevator/) [Noble Desktop](https://careerkarma.com/schools/noble-desktop/) [Hack Reactor by Galvanize](https://careerkarma.com/schools/hack-reactor/) [View More Schools](https://careerkarma.com/schools/) Tech Bootcamp Prep Research [How to Choose a Coding Bootcamp](https://careerkarma.com/blog/how-to-choose-a-coding-bootcamp/) [Coding Bootcamps with Job Placement Guarantees](https://careerkarma.com/blog/coding-bootcamp-job-placement-rates/) [Accelerated Six Week Coding Bootcamps](https://careerkarma.com/blog/six-week-coding-bootcamp/) [How to Get Into a Coding Bootcamp](https://careerkarma.com/blog/how-to-get-into-coding-bootcamp/) [Preparing for your Coding Bootcamp Interview](https://careerkarma.com/blog/coding-bootcamp-interview-questions/) [View More Bootcamp Prep Research](https://careerkarma.com/blog/bootcamp-prep/) Rankings [Best Coding Bootcamps](https://careerkarma.com/rankings/best-coding-bootcamps/) [Best Online Bootcamps](https://careerkarma.com/rankings/best-online-bootcamps/) [Best Web Design Bootcamps](https://careerkarma.com/rankings/best-web-design-bootcamps/) [Best Data Science Bootcamps](https://careerkarma.com/rankings/best-data-science-bootcamps/) [Best Technology Sales Bootcamps](https://careerkarma.com/rankings/best-technology-sales-bootcamps/) [Best Data Analytics Bootcamps](https://careerkarma.com/rankings/best-data-analytics-bootcamps/) [Best Cyber Security Bootcamps](https://careerkarma.com/rankings/best-cyber-security-bootcamps/) [Best Digital Marketing Bootcamps](https://careerkarma.com/rankings/best-digital-marketing-bootcamps/) [View More Rankings](https://careerkarma.com/schools/) Locations [Atlanta](https://careerkarma.com/locations/atlanta/) [Boston](https://careerkarma.com/locations/boston/) [Chicago](https://careerkarma.com/locations/chicago/) [London](https://careerkarma.com/locations/london/) [Los Angeles](https://careerkarma.com/locations/los-angeles/) [Miami](https://careerkarma.com/locations/miami/) [New York City](https://careerkarma.com/locations/new-york/) [San Francisco](https://careerkarma.com/locations/san-francisco/) [Seattle](https://careerkarma.com/locations/seattle/) [Toronto](https://careerkarma.com/locations/toronto/) [View More Locations](https://careerkarma.com/locations/) Paying for a Tech Bootcamp [How to Pay for Coding Bootcamp](https://careerkarma.com/blog/how-to-pay-for-coding-bootcamp/) [Understanding Coding Bootcamps with Deferred Tuition](https://careerkarma.com/blog/best-coding-bootcamps-with-deferred-tuition/) [GI Bill and Coding Bootcamps](https://careerkarma.com/blog/gi-bill-coding-bootcamps/) [Guide to Coding Bootcamp Scholarships](https://careerkarma.com/blog/coding-bootcamp-scholarships/) [View More Bootcamp Payment Resources](https://careerkarma.com/blog/bootcamp-financing/) Subjects [Python](https://careerkarma.com/subjects/best-python-bootcamps/) [Artificial Intelligence](https://careerkarma.com/subjects/best-artificial-intelligence-bootcamps/) [Back End](https://careerkarma.com/subjects/best-back-end-bootcamps/) [Machine Learning](https://careerkarma.com/subjects/best-machine-learning-bootcamps/) [Penetration Testing](https://careerkarma.com/subjects/best-penetration-testing-bootcamps/) [JavaScript](https://careerkarma.com/subjects/best-javascript-bootcamps/) [Java](https://careerkarma.com/subjects/best-java-bootcamps/) [SQL](https://careerkarma.com/subjects/best-sql-bootcamps/) [React](https://careerkarma.com/subjects/best-react-bootcamps/) [Golang](https://careerkarma.com/subjects/best-golang-bootcamps/) [View More Subjects](https://careerkarma.com/subjects/) Comparisons [App Academy vs Hack Reactor by Galvanize](https://careerkarma.com/comparison/app-academy-vs-hack-reactor/) [Fullstack Academy vs Hack Reactor by Galvanize](https://careerkarma.com/comparison/fullstack-academy-vs-hack-reactor/) [Flatiron School vs Springboard](https://careerkarma.com/comparison/flatiron-school-vs-springboard/) [Brainstation vs Coding Dojo](https://careerkarma.com/comparison/brainstation-vs-coding-dojo/) [Flatiron School vs App Academy](https://careerkarma.com/comparison/flatiron-school-vs-fullstack-academy/) [CareerFoundry vs DesignLab](https://careerkarma.com/comparison/careerfoundry-vs-designlab/) [Springboard vs TripleTen](https://careerkarma.com/comparison/springboard-vs-tripleten/) [General Assembly vs TripleTen](https://careerkarma.com/comparison/general-assembly-vs-tripleten/) [Coding Temple vs General Assembly](https://careerkarma.com/comparison/coding-temple-vs-general-assembly/) [View More Comparisons](https://careerkarma.com/comparison/) Start your Tech training Find, compare, and enroll in the right training program. Save on Tuition. Explore your training options and get exclusive tuition discounts ![Select Arrow](https://careerkarma.com/blog/wp-content/uploads/2024/02/white-arrow-40x32.png)
Readable Markdown
## How to Use C++ Queues In programming, queues are used to create data structures using the first-in, first-out (FIFO) approach. When you’re programming in C++, you may decide that you want to store a particular set of values in a FIFO structure. For instance, if you’re creating an app that stores a list of orders at a coffee shop, you would want them to be stored in a FIFO order. That’s where the C++ queue comes in. This tutorial will discuss the basics of queues, how to use queues in C++ to store data, and explore the main methods used to work with queues in C++. By the end of this tutorial, you’ll be an expert at using the C++ queue structure. ## C++ Queues Queues are a type of container adaptor in C++. They are used to implement a first-in, first-out (FIFO) data structure in programming. This structure means that the first item in a queue will be the first one on which an operation is performed. Elements are inserted and stored in the FIFO order. For instance, if you want to remove an item from a queue, the first one to be removed will be the first one in the queue. One example we could use to demonstrate the queue structure would be to think about shopping at a store. The first person who goes in line to check out will be the first one to be served; the second person in the queue will be served next, and so on. To declare a queue in C++, we must use the queue package. This package allows us to use queues in our code. We can use the following code to include the queue package in our code: ``` #include <queue> ``` Now that we’ve imported queue into our code, we can start working with the queue data structure. ## Declare a Queue in C++ Declaring a queue is another term used to describe the process of creating a queue. So, when you declare a C++ queue, you are telling your program that a queue should be created. Here’s the syntax that is used to declare a queue in C++: ``` queue <dataType> queueName; ``` Let’s break this down. Here are the three main components in our queue: - **queue** instructs our program to create a queue. - **dataType** is the type of data that is to be stored in our queue. - **queueName** is the name of our queue. Suppose we are operating a coffee shop and we are building a program which keeps track of our orders. Our program should use a queue to store the names of customers who have ordered a coffee so our baristas know who to serve in what order. We could use the following code to declare a queue to serve this purpose: ``` queue <string> pendingOrders; ``` In our code, we have declared a queue called `pendingOrders`. This queue can store string values. ## Add Item to a C++ Queue C++ queues are used to store data, which means that there are a number of features we can use to manipulate the contents of a queue. The `push()` method is used to add an item to a C++ queue. `push()` accepts one parameter, which is the value of the item you want to add to a specified queue. Let’s return to the coffee shop example from earlier to demonstrate the `push()` method in action. Suppose we have just opened our store and two customers have placed an order: Holly and Jim. Holly was first to place an order, then Jim placed his order. We could use the following code to add Holly and Jim to our queue: ``` #include <iostream> #include <queue> #include <string> int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); return 0; } ``` In this example, we have added Holly and Jim to our queue called `pendingOrders` in that order. Our code returns 0, which tells us that our code has finished running. Let’s break down our code. First, we import the queue and string libraries which are used to work with the queue data structure and string data type, respectively. We then use the queue method to create a queue called `pendingOrders`. This queue is capable of storing string values. Next we use the `push()` method to add Holly’s name to our queue, and we use `push()` to add Jim’s name to the queue on the next line. This means that Holly is first in our queue, and Jim is second in our queue. Here’s what our queue looks like: | | |---| | **Item** | | Holly | | Jim | ## Remove Item from a C++ Queue The `pop()` method is used to remove an item from a queue in C++. The pop() function removes the item at the first position in the queues, because queues use the first-in, first-out data structure. Suppose our barista has just processed Holly’s coffee order and wants to remove Holly’s name from the list of pending orders. We could use the following code to accomplish this task: ``` #include <iostream> #include <queue> #include <string> int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); pendingOrders.pop(); return 0; } ``` In this example, we have added Holly and Jim to our queue called `pendingOrders`. Then we used the `pop()` method to remove the first item in our queue. Our code returns 0, to indicate that our program has finished running. Here’s what our queue looks like now that we have removed Holly’s name from the queue: ![Venus profile photo](https://careerkarma.com/blog/wp-content/uploads/2024/02/venus.webp) "Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!" Venus, Software Engineer at Rockbot | | |---| | **Item** | | Jim | As you can see, our queue only has one item remaining, which is Jim’s name. ## Retrieve Item from a C++ Queue The `front()` and `back()` methods are used to retrieve the items at the front and the back of a queue in C++. ### C++ Queue front Suppose our barista wants to know the next order that is pending so they can start working on brewing the customer’s coffee. We could use the following code to find out the name of the next customer whose order is pending: ``` #include <iostream> #include <queue> #include <string> int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); cout << pendingOrders.front() } ``` Our code returns: `Holly`. In our code, we first declare a queue called `pendingOrders` and add the names Holly and Jim to the queue (in that order). We then use the `front()` method to retrieve the item at the front of the queue, and we print it to the console using cout. ### C++ Queue back Let’s say that our barista wants to know the most recent order placed in our queue. This is the order at the back of the queue, because queues use the first-in, first-out structure. We could use the `back()` method to retrieve the most recent order placed in the queue: ``` #include <iostream> #include <queue> #include <string> int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); cout << pendingOrders.back() } ``` Our code returns: `Jim`. In this example, we have initialized a queue and assigned it the values Holly and Jim like we did in our example using the `front()` method. But instead of using `front()` to print the first item in our queue, we use `back()` to print the last item in our queue. Because Jim was added last to our queue, his name was returned by the `back()` method. ## Print a C++ Queue When you’re working with queues in C++, you may decide that you want to print the contents of a queue to the console. C++ does not include any specific method that is used to print a queue to the console, but we can use a while loop to print out the contents of a queue. For instance, suppose we wanted to print out a list of our pending orders at the coffee shop so that our baristas know who to serve in what order. We could use the following code to accomplish this goal: ``` #include <iostream> #include <queue> #include <string> include namespace std; void showQueue(queue <string> pendingOrders) { queue <string> orders = pendingOrders; while (!orders.empty()) { cout << "\t" << orders.front(); orders.pop(); } cout << "\n"; } int main() { queue <string> pendingOrders; pendingOrders.push("Holly"); pendingOrders.push("Jim"); showQueue(pendingOrders); } ``` Our code returns: ``` Holly Jim ``` Let’s break down our code. In our example, we have declared a function called showQueue which accepts a queue called `pendingOrders` as a parameter. This function creates a new queue called orders, then uses a while loop to print out every item in the queue. The while loop uses the `empty()` method to check if the orders queue is empty. `!empty()` means that the while loop should run until the orders queue is empty. The while loop in our code executes the following steps: 1. A new tab character (`\t`) is printed to the console, followed by the first item in the orders queue. This item is accessed using the `front()` method. 2. The first item in the orders queue is removed using `pop()`. This allows our while loop to retrieve the contents of the next item in our queue on its next iteration. In our main program, we first create a queue called `pendingOrders`, then we add Holly and Jim to our queue. Finally, we invoke the `showQueue()` method which prints out the contents of the `pendingOrders` queue that we specified as a parameter to `showQueue()`. ## Other Queue Methods There are four additional C++ queue methods that you may want to use in your code. Here is a reference table with a brief description of each of these methods: | | | |---|---| | **Method** | **Description** | | size() | Returns the size of the queue. | | emplace() | Inserts new elements in the queue above the last element in the queue. | | swap() | Swaps the contents of two containers. | | empty() | Checks whether a queue is empty. Returns true if a queue is empty, and false if a queue contains one or more values. | ## Conclusion The queue structure is used in C++ to create queues. Queues leverage the first-in, first-out data structure, which means the first item in the queue is the first one which will leave the queue when an item is removed. This tutorial discussed, with references to examples, the basics of queues in C++, and how to perform common operations on a C++ queue such as adding and removing array items using push and pop. Now you’re ready to start working with C++ queues like an expert developer\!
Shard143 (laksa)
Root Hash9167054015464201743
Unparsed URLcom,careerkarma!/blog/c-plus-plus-queue/ s443