C++queue的详细使用
时间: 2024-05-04 08:19:39 浏览: 25
C++ STL 库中的 queue 是一个模板类,用于实现队列功能。以下是 queue 的详细使用方法:
## 头文件
```c++
#include <queue>
```
## 定义队列
```c++
queue<int> q; // 定义一个 int 类型的队列
```
## 入队
```c++
q.push(1); // 将元素 1 入队
```
## 出队
```c++
q.pop(); // 弹出队首元素
```
## 访问队首元素
```c++
int front_element = q.front(); // 获取队首元素
```
## 访问队尾元素
```c++
int back_element = q.back(); // 获取队尾元素
```
## 队列大小
```c++
int size = q.size(); // 获取队列大小
```
## 判断队列是否为空
```c++
bool is_empty = q.empty(); // 判断队列是否为空
```
需要注意的是,queue 是一种先进先出(FIFO)的数据结构,即先入队的元素先出队。如果需要使用后进先出(LIFO)的数据结构,可以使用 stack。
相关问题
C++queue的详细使用代码
以下是一个简单的使用C++ STL中queue的示例代码:
```cpp
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<int> q;
// 添加元素到队列尾部
q.push(10);
q.push(20);
q.push(30);
// 访问队首元素
cout << "队首元素为: " << q.front() << endl;
// 访问队尾元素
cout << "队尾元素为: " << q.back() << endl;
// 弹出队首元素
q.pop();
// 遍历队列
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
return 0;
}
```
这个程序首先创建了一个空队列q,然后使用`q.push()`将三个整数10、20和30加入队列。接着,使用`q.front()`和`q.back()`函数分别访问队首和队尾元素。接下来,使用`q.pop()`函数弹出队首元素10。最后,使用`while`循环遍历队列并弹出所有元素。
执行该程序将输出:
```
队首元素为: 10
队尾元素为: 30
20 30
```
c++queue库函数的使用
C++中的queue库函数用于实现队列数据结构。下面是一些常用的queue库函数的使用介绍:
1. push(element):将元素element添加到队列的末尾。
2. pop():移除队列的第一个元素。
3. front():返回队列的第一个元素,但不移除它。
4. back():返回队列的最后一个元素,但不移除它。
5. empty():检查队列是否为空,如果为空则返回true,否则返回false。
6. size():返回队列中元素的个数。
以下是一个使用queue库函数的示例代码:
```cpp
#include <iostream>
#include <queue>
int main() {
std::queue<int> myQueue;
// 添加元素到队列
myQueue.push(10);
myQueue.push(20);
myQueue.push(30);
// 输出队列的大小
std::cout << "Queue size: " << myQueue.size() << std::endl;
// 输出队列的第一个元素
std::cout << "Front element: " << myQueue.front() << std::endl;
// 移除队列的第一个元素
myQueue.pop();
// 输出队列的第一个元素
std::cout << "Front element after pop: " << myQueue.front() << std::endl;
// 检查队列是否为空
if (myQueue.empty()) {
std::cout << "Queue is empty" << std::endl;
} else {
std::cout << "Queue is not empty" << std::endl;
}
return 0;
}
```
运行以上代码,输出结果为:
```
Queue size: 3
Front element: 10
Front element after pop: 20
Queue is not empty
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)