Use of queue<t> class in C # and source analysis of some methods

Source: Internet
Author: User

Queue<t> class

represents an FIFO collection of objects.

queues are useful for storing messages in the order in which they are received for sequential processing. Objects stored in the queue,<t> are inserted at one end and removed from the other end.

the queue<t> capacity is the number of elements that the Queue<t> can contain. When you add elements to Queue<t>, the capacity is automatically increased as needed by reallocating the internal array.

you can reduce capacity by calling TrimExcess.

Queue<t> accept NULL as a valid value for the reference type and allow duplicate elements.

named control: System.Collections.Generic

Assembly: System (in System.dll)

syntax: public class Queue<t>:ienumerable<T>, ICollection, IEnumerable

List<t> implements IList<t>, ICollection<t>, IEnumerable<T >, IList, ICollection, IEnumerable interface

so you can see that compared to list<t>:

Queue<t> does not inherit the ICollection<t> interface because the Add () and remove () methods defined by this interface cannot be used for queues;

Queue<t> does not inherit the IList<t> interface, so you cannot use the indexer to access the queues.

so the queue only allows elements to be added at the end of the queue, taking elements from the head of the queue.

members of the common queue<t> class:

count: Returns the number of elements in the queue.

Enqueue: Adds an element at one end of the queue.

Dequeue (): reads and deletes an element from the head of the queue. If Dequeue () is called, an exception InvalidOperationException exception is thrown when there are no elements in the queue.

Peek (): Takes an element out of the head of the queue, but does not delete it.

trimexcess (): Resets the capacity of the queue.

/********************************************************************************************************** ********************/

The source code for the member functions of the common queue<t> class is as follows:

Public T Dequeue ()

{

if (this._size = = 0)

{

throwhelper.throwinvalidoperationexception (exceptionresource.invalidoperation_emptyqueue);

}

T local = This._array[this._head];

This._array[this._head] = default (T);

This._head = (this._head + 1)% This._array. Length;

this._size--;

this._version++;

return local;

}

Public void Enqueue (T item)

{

if (this._size = = This._array. Length)

{

int capacity = (int) ((This._array. Length * 200L)/100L);

if (Capacity < (This._array. Length + 4))

{

capacity = This._array. Length + 4;

}

This . Setcapacity (capacity);

}

This._array[this._tail] = Item;

This._tail = (this._tail + 1)% This._array. Length;

this._size++;

this._version++;

}

Public T-Peek ()

{

if (this._size = = 0)

{

throwhelper.throwinvalidoperationexception (exceptionresource.invalidoperation_emptyqueue);

}

return this._array[this._head];

}

Public void TrimExcess ()

{

int num = (int) (This._array. Length * 0.9);

if (This._size < num)

{

This . Setcapacity (this._size);

}

}

The source code for the Setcapacity function used by the appeal method is as follows:

private void setcapacity (int capacity)

{

t[] Destinationarray = new t[capacity];

if (this._size > 0)

{

if (This._head < This._tail)

{

array.copy (This._array, This._head, Destinationarray, 0, this._size);

}

Else

{

array.copy (This._array, This._head, Destinationarray, 0, This._array. Length-this._head);

array.copy (this._array, 0, Destinationarray, This._array. Length-this._head, this._tail);

}

}

This._array = destinationarray;

this._head = 0;

This._tail = (This._size = = capacity)? 0:this._size;

this._version++;

}

/********************************************************************************************************** *******************************/

Example:

The following code example demonstrates several methods of the queue<t> generic class. This code example creates a string queue with a default capacity, and uses the Enqueue method to queue five strings. Enumerates the queue elements, which do not change the state of the queue. Use the Dequeue method to dequeue the first string. Use the Peek method to find the next item in the queue, and then use the Dequeue method to dequeue the item.

use the ToArray method to create an array and copy the queue elements to the array, and then pass the array to the accepted IEnumerableQueue constructor to create a copy of the queues. The elements of the copy are displayed.

Create an array that is twice times the size of the queue and use the CopyTo method to start copying the array elements from the middle of the array. Use the Queue1t> constructor again to create a second copy of the queue, which contains three null elements at the beginning.

Use the Contains method to display the string "Four" in the first queue copy, and then use the clear method to clear the copy and display the queue column as empty by the Count property.

Using System;

Using System.Collections.Generic;

Class Example

{

public static void Main ()

{

queue1string> numbers = new queue1string> ();

Numbers. Enqueue ("one");

Numbers. Enqueue ("both");

Numbers. Enqueue ("three");

Numbers. Enqueue ("four");

Numbers. Enqueue ("five");

A queue can be enumerated without disturbing its contents.

foreach (string number in numbers)

{

Console.WriteLine (number);

}

Console.WriteLine ("\ndequeuing ' {0} '", numbers. Dequeue ());

Console.WriteLine ("Peek at next item to dequeue: {0}", numbers. Peek ());

Console.WriteLine ("Dequeuing ' {0} '", numbers. Dequeue ());

Create a copy of the queue, using the ToArray method and the

Constructor that accepts an IEnumerable.

queue1string> queuecopy = new queue1string> (numbers. ToArray ());

Console.WriteLine ("\ncontents of the first copy:");

foreach (string number in queuecopy)

{

Console.WriteLine (number);

}

Create an array twice the size of the queue and copy the

Elements of the queue, starting at the middle of the

Array.

string[] array2 = new string[numbers. Count * 2];

Numbers. CopyTo (array2, numbers. Count);

Create a second queue, using the constructor that accepts an

IEnumerable (of T).

queue1string> queueCopy2 = new queue1string> (array2);

Console.WriteLine ("\ncontents of the second copy, with duplicates and nulls:");

foreach (string number in queueCopy2)

{

Console.WriteLine (number);

}

Console.WriteLine ("\nqueuecopy.contains (\" four\ ") = {0}", Queuecopy.contains ("four"));

Console.WriteLine ("\nqueuecopy.clear ()");

Queuecopy.clear ();

Console.WriteLine ("\nqueuecopy.count = {0}", Queuecopy.count);

}

}

/* This code example produces the following output:

One

Both

Three

Four

Five

Dequeuing ' One '

Peek at next item to Dequeue:two

Dequeuing ' both '

Contents of the copy:

Three

Four

Five

Contents of the second copy, with duplicates and nulls:

Three

Four

Five

Queuecopy.contains ("four") = True

Queuecopy.clear ()

Queuecopy.count = 0

*/

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Use of queue<t> class in C # and source analysis of some methods

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.