STL-queue.back()队尾误区

本文解析了C++标准库queue的back()方法指向最新插入元素,而front()指向最早插入的元素。重点介绍了如何区别两者并展示了如何在代码中运用它们。同时指出,队列为空时应使用empty而非back进行检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

queue.back()指向最新插入queue中的值,而非队尾元素,

如:queue.pop()多次,并不会影响queue.back()的值。

STL 英文back()解释:

reference& back();
const_reference& back() const;

Access last element

Returns a reference to the last element in the queue. This is the "newest" element in the queue (i.e. the last element pushed into the queue).
This member function effectively calls member back of the underlying container object.

queue.front()指向最旧插入queue的元素值。

STL 英文front()解释:

reference& front();
const_reference& front() const;

Access next element

Returns a reference to the next element in the queue.

The next element is the "oldest" element in the queue and the same element that is popped out from the queue when queue::pop is called.

This member function effectively calls member front of the underlying container object.

判断队列为空使用empty或者front,不能使用back查看。

// queue::front
#include <iostream>       // std::cout
#include <queue>          // std::queue

int main ()
{
  std::queue<int> myqueue;

  myqueue.push(77);
  myqueue.push(16);
  std::cout<<myqueue.back()<<std::endl;
  std::cout<<myqueue.front()<<std::endl;
  myqueue.pop();
   std::cout<<myqueue.back()<<std::endl;
  std::cout<<myqueue.front()<<std::endl;
  myqueue.pop();
   std::cout<<myqueue.back()<<std::endl;
  std::cout<<myqueue.front()<<std::endl;
  
  std::cout << "myqueue.front() is now " << myqueue.front() << '\n';

  return 0;
}

queue::front - C++ Reference

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chde2Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值