c++ std::queue操作
时间: 2023-08-03 17:47:12 浏览: 142
`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` 不支持随机访问,因此不能像数组或向量那样使用下标操作符 `[]` 来访问队列中的元素。
阅读全文
相关推荐















