STL中queue详解

来源:互联网 发布:吉利知豆电动汽车租赁 编辑:程序博客网 时间:2024/05/18 16:17

queue

queues are a type of container adaptor, specifically designed to operate in a FIFO context (first-in first-out), where elements are inserted into one end of the container and extracted from the other.

The standard container classes deque and list fulfill these requirements. By default, if no container class is specified for a particular queue class instantiation, the standard container deque is used.

C++ STL 的队列泛化是直接通过现有的序列容器来实现的,默认使用双端队列deque的数据结构,当然,可以采用其他线性结构( list),只要提供堆栈的入队、出队、队尾/队头元素访问和判断是否为空的操作即可。由于队列的底层使用的是其他容器,因此,队列可看做是一种适配器,将一种容器转换为另一种容器(队列容器)。

  • queue
  • Member functions
    • 构造器constructor
    • empty
    • back
    • front
    • pop
    • push
    • size
    • swap


Member functions

构造器(constructor)

Constructs a queue container adaptor object.

  std::deque<int> mydeck (3,100);        // deque with 3 elements  std::list<int> mylist (2,200);         // list with 2 elements  std::queue<int> first;                 // empty queue  std::queue<int> second (mydeck);       // queue initialized to copy of deque  std::queue<int,std::list<int> > third; // empty queue with list as underlying container  std::queue<int,std::list<int> > fourth (mylist);

empty

Returns whether the stack is empty: i.e. whether its size is zero.

判断栈是否为空

back

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).

返回队尾元素

front

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.

返回队尾元素

pop

Removes the next element in the queue, effectively reducing its size by one.

The element removed is the “oldest” element in the queue whose value can be retrieved by calling member queue::front.

弹出队头

push

Inserts a new element at the end of the queue, after its current last element. The content of this new element is initialized to val.

入队到队尾

// #include <iostream>       // std::cout#include <queue>          // std::queueint main (){  std::queue<int> myqueue;  int sum (0);  for (int i=1;i<=10;i++) myqueue.push(i);  while (!myqueue.empty())  {     sum += myqueue.front();     myqueue.pop();  }  std::cout << "total: " << sum << '\n';  return 0;}

Output:

total: 55

size

Returns the number of elements in the queue.

返回队列元素的个数

swap

Exchanges the contents of the container adaptor (*this) by those of x.

交换两个队列

// queue::swap#include <iostream>       // std::cout#include <queue>          // std::queueint main (){  std::queue<int> foo,bar;  foo.push (10); foo.push(20); foo.push(30);  bar.push (111); bar.push(222);  foo.swap(bar);  std::cout << "size of foo: " << foo.size() << '\n';  std::cout << "size of bar: " << bar.size() << '\n';  return 0;}

Output:

size of foo: 2
size of bar: 3

0 0
原创粉丝点击