c++ std::queue出队并访问出队元素
时间: 2023-08-05 17:04:25 浏览: 41
对于 `std::queue` 容器适配器来说,访问队列头部的元素可以使用 `front()` 方法,而弹出队列头部的元素可以使用 `pop()` 方法。因此,出队并访问出队元素的代码如下所示:
```c++
#include <iostream>
#include <queue>
int main() {
std::queue<int> q;
q.push(1);
q.push(2);
q.push(3);
while (!q.empty()) {
int front_element = q.front(); // 访问队列头部元素
std::cout << front_element << " "; // 输出队列头部元素
q.pop(); // 弹出队列头部元素
}
return 0;
}
```
在这个示例中,我们先往队列中插入了三个元素 `1`、 `2` 和 `3`,然后使用 `while` 循环遍历队列中的元素,每次循环中都会访问队列头部的元素并输出,然后弹出队列头部的元素。最终输出的结果为 `1 2 3`,表示队列中的元素已经全部出队并被访问了。
相关问题
std::queue出队入队
在 C++ 中,`std::queue` 是一个容器适配器,用于实现先进先出(FIFO)的队列。下面是 `std::queue` 的基本出队和入队操作:
1. 入队操作:使用 `push()` 方法将元素插入队列尾部。
```cpp
#include <queue>
std::queue<int> myQueue;
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
```
2. 出队操作:使用 `pop()` 方法将队列头部的元素移除。
```cpp
myQueue.pop();
```
3. 访问队首元素:使用 `front()` 方法访问队列头部元素的值。
```cpp
int firstElement = myQueue.front();
```
需要注意的是,`front()` 方法只是返回队头元素的值,并不会移除队头元素。如果需要移除队头元素,还需要调用 `pop()` 方法。
另外,如果队列为空,调用 `front()` 或 `pop()` 方法会导致未定义的行为,因此在访问队列元素之前先要判断队列是否为空,可以使用 `empty()` 方法进行判断:
```cpp
if (!myQueue.empty()) {
int firstElement = myQueue.front();
myQueue.pop();
}
```
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` 不支持随机访问,因此不能像数组或向量那样使用下标操作符 `[]` 来访问队列中的元素。