Analysis of STL source code [container] (vi) [stl_queue.h]

Source: Internet
Author: User
Tags documentation


The definition of the queue template class is in the <queue> header file. Similar to the Stack template class, the queue template class also requires two template parameters, one is the element type, one container type, the element type is necessary, the container type is optional, and the default is the Deque type.
The sample code that defines the queue object is as follows:
Queue<int> Q1;

Queue<double> Q2;

The basic operations of the queue are:
Join the team, as an example: Q.push (x); Connect X to the end of the queue.
Out of the team, as an example: Q.pop (); The first element of the pop-up queue, note that the value of the pop-up element is not returned.
Access the first element of the team, as an example: Q.front (), the element that was first pressed into the queue.
Access the tail element of the team, as an example: Q.back (), the element that was last pressed into the queue.
Determines that the queue is empty, as an example: Q.empty (), returns True when the queue is empty.
Access the number of elements in the queue, as an example: Q.size ()

Stl_queue.h's source code:

Filename:stl_queue.h//Comment by: Frost//e-mail:mdl2009@vip.qq.com//BLOG:HTTP://BLOG.CSDN.NET/MD l13412//////////////////////////////////////////////////////////////////////////////////queue is an advanced first-in First out, FIFO data structure//It has two exits before and after, becoming the team head and team tail//queue allows you to append elements and access team tail elements at the end of the team, acquire and remove elements from the team header/////Otherwise it does not support access to other elements/////////////////// The following is the layout for using deque////Support front () and pop () support BAC                K () and push ()//↓↓//team head, Team tail//↓   ↓//---------------------------------------------------------------------//|   | |   ...... |   | |   ...... |   |   | |   ......  |   | |
X |                     ---------------------------------------------------------------------//↑↑↑                    ↑//|                    |                     |
| // ----------------------                    -----------------------//Here is unused reserved memory, possibly 0 here is unused reserved memory, possibly 0/////////////////////// ///////////////////////////////////////////////////////////

//////////////////////////////////////////////////// Priority_queue is a type that allows the user to press any element into the container in any order,//But it must be taken out of the highest priority element when the element is fetched///the vector is used as the container by default , the default priority comparison using the less//algorithm is to use the Binary-heap////////////////////////////////////////////////////////////////////////////                                              The following is the principle model of the container using vector, priority comparison resolution with less////Team tail, support push ()// ↓//--------------------------------------------------------//Support POPs () and to   P ()--->|   | |   ...... |   |   |   | |   ......  |   | |
X |                --------------------------------------------------------//↑                ↑↑//| -----------------------//Internal use is heap here is unused reserved memory, possibly 0//////////////////////////////////////////////////                                  The following is the use of vector, priority comparison resolution in the case of less a implementation skills,//borrowed is the example of Houtie teacher, this practice is not used in this technique/
[A]//|                               //                   ---------------------------------
//                   |
|                               [B] [C]//|
|                     //        -----------------------         -----------------------
//        |         |                     |
|                     [D] [E] [F] [G]//|
|
//   -----------                |         //   |                |
|                                                   [H] [I] [J]//vector reserved memory, up to 0// ------------------//↓↓//--------------------------------------------- -----------------------------
// | Not use | A | B | C | D | E | F | G | H | I |   J | |   ...... | |
End | --------------------------------------------------------------------------////specific algorithm please refer to any one of the algorithm books, if not, throw it:-)//// * * * Copyright (c) 1994 * Hewlett-packa RD Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any PURPO SE is hereby granted without fee, * provided this above copyright notice appear in all copies and * That's both that C  Opyright Notice and this permission notice appear * in supporting documentation.  Hewlett-Packard Company makes no * representations about the suitability of this software to any * purpose.
 It is provided ' as is ' without express or implied warranty. * * * Copyright (c) 1996,1997
 * Silicon Graphics Computer Systems, Inc.  * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby Granted without fee, * provided that above copyright notice appear in all copies and * that both  Ice and this permission notice appear * in supporting documentation.  Silicon Graphics makes no * representations about the suitability of this software to any * purpose.
 It is provided ' as is ' without express or implied warranty.
 */* Note:this is a internal header file, included by the other STL headers.
 * You should not attempt to use it directly. * * #ifndef __sgi_stl_internal_queue_h #define __SGI_STL_INTERNAL_QUEUE_H __stl_begin_namespace// If the compiler cannot deduce the default parameter type that is used later based on the preceding template parameter,//Then it is necessary to manually specify that the Deque////is used by default for the queue internal container, which is very suitable for use with deque when it is required to append elements at the end of the team.  ifndef __stl_limited_default_templates Template <class T, class Sequence = deque<t> > #else template <class T, ClasS sequence> #endif class Queue {//interpretation of operators in <stl_pair.h> analysis friend BOOL operator== __stl_null_tmpl_args (const
  queue& x, const queue& y);

friend BOOL operator< __stl_null_tmpl_args (const queue& x, const queue& y); Public://Because the queue only supports operations on the team head and tail, it does not define STL requirements//pointer, iterator, difference_type typedef typename SEQUENCE::VALUE_T
  Ype Value_type;
  typedef typename SEQUENCE::SIZE_TYPE Size_type;
  typedef typename Sequence::reference Reference;

typedef typename Sequence::const_reference Const_reference;   Protected:sequence C;  This is the container we actually maintain public://These are standard interfaces for STL queue, calling the container's member function for implementation//interface and stack implementations very close, reference <stl_stack.h> bool Empty ()
  const {return c.empty ();}
  Size_type size () const {return c.size ();}
  Reference Front () {return C.front ();}
  Const_reference Front () const {return C.front ();}
  Reference back () {return c.back ();}
  Const_reference back () const {return c.back ();} void push (const value_type& x) { C.push_back (x);

void Pop () {C.pop_front ();}}; For detailed explanation see <stl_pair.h> template <class T, class sequence> bool operator== (const queue<t, sequence>& x

, const queue<t, sequence>& y) {return x.c = = y.c;} Template <class T, class sequence> bool operator< (const queue<t, sequence>& x, const queue<t, Sequen

ce>& y) {return x.c < y.c;} #ifndef __stl_limited_default_templates Template <class T, class Sequence = Vector<t>, Class Compare =  Less<typename sequence::value_type> > #else template <class T, class Sequence, class Compare> #endif class
  priority_queue {Public:typedef typename sequence::value_type value_type;
  typedef typename SEQUENCE::SIZE_TYPE Size_type;
  typedef typename Sequence::reference Reference;

typedef typename Sequence::const_reference Const_reference;           Protected:sequence C;         Internal maintenance of the container Compare comp; Priority decision-making discriminant Public:priority_queue(): C () {}//user can specify their own priority decision function explicit Priority_queue (const compare& x): C (), comp (x) {}//use [First, last] area Inter-tectonic priority_queue #ifdef __stl_member_templates template <class inputiterator> priority_queue (InputIterator Fir
  St, Inputiterator last, const compare& x): C (A, last), comp (x) {make_heap (C.begin (), C.end (), comp); Template <class inputiterator> priority_queue (Inputiterator-I, Inputiterator last): C (A, last) {make _heap (C.begin (), C.end (), comp); #else/* __stl_member_templates/priority_queue (const value_type*-I, const value_type* last, CO
  NST compare& x): C (A, last), comp (x) {make_heap (C.begin (), C.end (), comp); } priority_queue (const value_type*, const value_type* last): C (A, last) {Make_heap (C.begin (), C.end (), C OMP);
  #endif/* __stl_member_templates *//STL Priority_queue Standard interface bool Empty () const {return c.empty ();} Size_type size () const {Return C.size ();

  //returns the highest priority element Const_reference top () const {return C.front ();}
      Inserts an element and adjusts the heap void push (const value_type& x) {__stl_try {c.push_back (x);
    Detailed analysis See <stl_heap.h> push_heap (C.begin (), C.end (), comp);
  } __stl_unwind (C.clear ()); }//eject the highest priority element void Pop () {__stl_try {//detailed analysis See <stl_heap.h> pop_heap (C.begin (), C.end (), Comp
      );
    C.pop_back ();
  } __stl_unwind (C.clear ());

}
};
 Do not provide comparison operations __stl_end_namespace #endif/* __sgi_stl_internal_queue_h *//local Variables://mode:c++//end:
/* 6 commonly used functions front (), Back
	(), push (), pop (), empty (), size ()
* * *
#include <stdio.h>
#include < Queue>

using namespace std;

int main ()
{
	int n, m, size;
	Queue <int> q;//defines queues Q

	q.push (1);
	Q.push (2);//press 1, 2 into queue while

	(!q.empty ())//To determine whether the queue is empty
	{
		n = q.front ();//return queue header data
		m = Q.back ();// Returns the queue tail data
		size = Q.size ();//Returns the number of data in the queue
		q.pop ();//queue header data out of Team
		printf ("%d%d%d\n", N, m, size);
	}
	return 0;
}

The following is a multithreaded operation in the STL queue:

    #include <queue> #include <boost/asio.hpp> #include <boost/bind.hpp> #include < boost/thread.hpp> #include <boost/thread/tss.hpp> #include <boost/thread/mutex.hpp> #incl  
      
      
    Ude <boost/thread/condition.hpp> #include <boost/date_time/posix_time/posix_time.hpp>  
    #include <iostream> using namespace std;  
      
      
    using namespace boost;  
    Boost::recursive_mutex Io_mutex;  
    Boost::condition_variable_any cond;  
      
    Std::queue<int> IQ;  
            Class Printer {public:printer (boost::asio::io_service& io,int N): Strand_ (IO),  
            Timer1_ (IO, boost::p osix_time::seconds (1)), timer2_ (IO, boost::p osix_time::seconds (1)),  
            Count_ (n) {timer2_.async_wait (Boost::bind (&printer::enqueue, this)); Timer1_.async_wait (boost::bind &printer::Dequeue, this));  
            } ~printer () {Boost::recursive_mutex::scoped_lock lock (Io_mutex);  
        Std::cout << "Final count is" << count_ << "\ n";  
            } void Dequeue () {Boost::recursive_mutex::scoped_lock lock (Io_mutex);         
             
            while (Iq.empty ()) {cond.wait (lock);  
            int pop = 0;  
                if (!iq.empty ()) {pop = Iq.front ();  
                Iq.pop ();  
            cout<< "------------Pop" <<pop<<endl;  
            
            } cond.notify_all ();  
            Timer1_.expires_at (Timer1_.expires_at () + boost::p osix_time::seconds (1));         
        Timer1_.async_wait (Boost::bind (&printer::d equeue, this)); } void Enqueue () {boOst::recursive_mutex::scoped_lock Lock (Io_mutex);             
            while (iq.size () = = 1000) {cond.wait (lock);  
            } iq.push (Count_);;  
            Cond.notify_all ();  
            cout<< "------------Push" <<count_<<endl;  
            Timer1_.expires_at (Timer1_.expires_at () + boost::p osix_time::seconds (1));            
        Timer1_.async_wait (Boost::bind (&printer::enqueue, this));  
        } Private:boost::asio::strand Strand_;  
        Boost::asio::d Eadline_timer timer1_;  
        Boost::asio::d Eadline_timer timer2_;  
    int Count_;  
      
      
    };  
        int main () {Thread_group threads;  
          
      
        Boost::asio::io_service io;  
        Printer * p[1000];  
        int num = 1000;  
      
            for (int i = 0; i < num i++) {P[i] = new Printer (io,i); ThreaDs.create_thread (Boost::bind (&boost::asio::io_service::run, &io));     
        } io.run ();  
         
      
        Threads.join_all ();  
        Std::system ("pause");  
    return 0;  
 }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.