C++ std::队列
时间: 2023-08-28 19:17:42 浏览: 45
C++ 中的 std::queue 是一个容器适配器,它是基于 deque 实现的队列。它提供了一组函数来实现队列的基本操作,如 push()、pop()、front()、back() 和 empty() 等。其中,push() 函数用于将元素插入队列的尾部,pop() 函数用于删除队列的头部元素,front() 函数用于返回队列头部元素的引用,back() 函数用于返回队列尾部元素的引用,empty() 函数用于判断队列是否为空。C++ 的 std::queue 还提供了一些其他的函数,如 size()、swap() 等。使用 std::queue 需要包含头文件 <queue>。
相关问题
c++ std::queue操作
`std::queue` 是 C++ 标准库中的一个容器适配器,它基于其他 STL 容器实现,提供了一个先进先出(FIFO)的队列数据结构。下面是 `std::queue` 常用的操作:
1. `push`:将元素添加到队列尾部。
```c++
std::queue<int> q;
q.push(1);
q.push(2);
q.push(3);
```
2. `pop`:将队列头部的元素删除。
```c++
std::queue<int> q;
q.push(1);
q.push(2);
q.push(3);
q.pop(); // 删除队列头部元素1
```
3. `front`:访问队列头部的元素。
```c++
std::queue<int> q;
q.push(1);
q.push(2);
q.push(3);
int front_element = q.front(); // 访问队列头部元素1
```
4. `back`:访问队列尾部的元素。
```c++
std::queue<int> q;
q.push(1);
q.push(2);
q.push(3);
int back_element = q.back(); // 访问队列尾部元素3
```
5. `empty`:判断队列是否为空。
```c++
std::queue<int> q;
if (q.empty()) {
std::cout << "队列为空" << std::endl;
}
```
6. `size`:获取队列中元素的数量。
```c++
std::queue<int> q;
q.push(1);
q.push(2);
q.push(3);
int size = q.size(); // 获取队列中元素数量,结果为3
```
需要注意的是,`std::queue` 不支持随机访问,因此不能像数组或向量那样使用下标操作符 `[]` 来访问队列中的元素。
c++ std::queque移除队头元素
在 C++ STL 中,`std::queue` 是一个先进先出的队列容器,支持在队尾插入元素,在队头删除元素,并且可以访问队头和队尾元素。
在 `std::queue` 中,移除队头元素可以使用 `pop()` 方法。该方法会将队列开头的元素从队列中移除,如果队列为空,则会导致未定义的行为。`pop()` 方法没有返回值。
以下是一个使用 `pop()` 方法移除队头元素的示例代码:
```c++
#include <iostream>
#include <queue>
int main() {
// 定义整型队列
std::queue<int> myQueue;
// 插入元素
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
// 移除队头元素
myQueue.pop();
// 访问队头和队尾元素
std::cout << "队头元素为:" << myQueue.front() << std::endl;
std::cout << "队尾元素为:" << myQueue.back() << std::endl;
return 0;
}
```
在上述代码中,我们首先定义了一个整型队列 `myQueue`,然后向队列中插入了三个元素 1、2 和 3。接着,我们调用了 `pop()` 方法,将队头元素 1 从队列中移除。最后,我们使用 `front()` 和 `back()` 方法访问了队头和队尾元素。
运行上述代码的输出结果为:
```
队头元素为:2
队尾元素为:3
```
需要注意的是,`pop()` 方法会修改原队列的内容,如果你需要保留原队列,可以将其赋值给一个新的队列进行操作。