Home Backend Development C#.Net Tutorial Detailed explanation of c++ priority queue usage

Detailed explanation of c++ priority queue usage

Feb 10, 2020 am 09:11 AM

Detailed explanation of c++ priority queue usage

c Detailed explanation of priority queue usage

Priority queue is also a kind of data structure such as queue. Its operation is not limited to first-in-first-out of the queue, but can also be done logically (exiting the queue according to the maximum value or minimum value, etc.).

Recommended learning: c Video tutorial

A normal queue is a first-in, first-out data structure. Elements are appended to the end of the queue and deleted from the head of the queue.

In a priority queue, elements are given priority. When elements are accessed, the element with the highest priority is removed first. The priority queue has the behavioral characteristics of first in, largest out.

First of all, we must include the header file #include. The difference between it and queue is that we can customize the priority of the data in it, so that the ones with higher priority will be placed at the front of the queue. Get priority out of the queue.

The priority queue has all the characteristics of the queue, including the basic operations of the queue. It just adds an internal sorting on this basis. It is essentially implemented as a heap.

The basic operation is the same as that of the queue:

top accesses the head element of the queue

empty whether the queue is empty

size returns the number of elements in the queue

push Insert elements to the end of the queue (and sort)

emplace Construct an element in place and insert it into the queue

pop Pop the element at the head of the queue

swap Exchange Content

Definition: priority_queue<Type, Container, Functional>

Type is the data type, Container is the container type (Container must be a container implemented with an array , such as vector, deque, etc., but list cannot be used. Vector is used by default in STL), and Functional is the comparison method.

When you need to use a custom data type, you need to pass in these three parameters. When using a basic data type, you only need to pass in the data type. The default is a big heap.

Generally:

//升序队列
priority_queue <int,vector<int>,greater<int> > q;
//降序队列
priority_queue <int,vector<int>,less<int> >q;

//greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)

1. Example of basic type priority queue:

#include<iostream>
#include <queue>
using namespace std;
int main() 
{
    //对于基础类型 默认是大顶堆
    priority_queue<int> a; 
    //等同于 priority_queue<int, vector<int>, less<int> > a;
    
    //      这里一定要有空格,不然成了右移运算符↓↓
    priority_queue<int, vector<int>, greater<int> > c;  //这样就是小顶堆
    priority_queue<string> b;

    for (int i = 0; i < 5; i++) 
    {
        a.push(i);
        c.push(i);
    }
    while (!a.empty()) 
    {
        cout << a.top() << &#39; &#39;;
        a.pop();
    } 
    cout << endl;

    while (!c.empty()) 
    {
        cout << c.top() << &#39; &#39;;
        c.pop();
    }
    cout << endl;

    b.push("abc");
    b.push("abcd");
    b.push("cbd");
    while (!b.empty()) 
    {
        cout << b.top() << &#39; &#39;;
        b.pop();
    } 
    cout << endl;
    return 0;
}

Running result:

4 3 2 1 0
0 1 2 3 4
cbd abcd abc
请按任意键继续. . .

2. Example of using pair as a priority queue element:

Rule: For pair comparison, compare the first element first, and compare the second element if the first one is equal.

#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() 
{
    priority_queue<pair<int, int> > a;
    pair<int, int> b(1, 2);
    pair<int, int> c(1, 3);
    pair<int, int> d(2, 5);
    a.push(d);
    a.push(c);
    a.push(b);
    while (!a.empty()) 
    {
        cout << a.top().first << &#39; &#39; << a.top().second << &#39;\n&#39;;
        a.pop();
    }
}

Run result:

2 5
1 3
1 2
请按任意键继续. . .

3. Example of using custom type as priority queue element

#include <iostream>
#include <queue>
using namespace std;

//方法1
struct tmp1 //运算符重载<
{
    int x;
    tmp1(int a) {x = a;}
    bool operator<(const tmp1& a) const
    {
        return x < a.x; //大顶堆
    }
};

//方法2
struct tmp2 //重写仿函数
{
    bool operator() (tmp1 a, tmp1 b) 
    {
        return a.x < b.x; //大顶堆
    }
};

int main() 
{
    tmp1 a(1);
    tmp1 b(2);
    tmp1 c(3);
    priority_queue<tmp1> d;
    d.push(b);
    d.push(c);
    d.push(a);
    while (!d.empty()) 
    {
        cout << d.top().x << &#39;\n&#39;;
        d.pop();
    }
    cout << endl;

    priority_queue<tmp1, vector<tmp1>, tmp2> f;
    f.push(b);
    f.push(c);
    f.push(a);
    while (!f.empty()) 
    {
        cout << f.top().x << &#39;\n&#39;;
        f.pop();
    }
}

Run result:

3
2
1
 
3
2
1
请按任意键继续. . .

The above is the detailed content of Detailed explanation of c++ priority queue usage. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
Using the Task Parallel Library (TPL) in C# Using the Task Parallel Library (TPL) in C# Jul 31, 2025 am 07:56 AM

C#'s TPL simplifies parallel task processing through the Task class. 1. Use Task.Run() or Task.Factory.StartNew() to start the task, and recommend the former; 2. Get the result through Task and wait for completion with await or .Result; 3. Use Task.WhenAll() to execute multiple tasks in parallel, pay attention to resource competition; 4. Use AggregateException to handle exceptions, and traverse specific errors after catching; 5. Use CancellationTokenSource to cancel the task, which is suitable for timeout or user cancellation scenarios; at the same time, pay attention to avoid mixing synchronous and asynchronous code to prevent deadlock problems.

How to read a text file line by line in C#? How to read a text file line by line in C#? Aug 02, 2025 am 06:52 AM

There are two common ways to read text files line by line in C#: using StreamReader and File.ReadLines(). 1. The ReadLine() method of StreamReader is suitable for processing large files, read line by line through loop and is memory friendly, and uses using to ensure resource release; 2. File.ReadLines() provides concise code, suitable for scenarios that only need to be traversed once, supports lazy loading and can specify encoding. If you need to access the file content multiple times, File.ReadAllLines() is recommended. The two automatically recognize encoding by default, but to avoid garbled code, it is recommended to explicitly specify Encoding.UTF8 and Enc as needed.

Leveraging C# for Scientific Computing and Data Analysis Leveraging C# for Scientific Computing and Data Analysis Aug 05, 2025 am 06:19 AM

C#canbeusedforscientificcomputinganddataanalysisbysettingupaproperenvironment,leveragingrelevantlibraries,andoptimizingperformance.First,installVisualStudioorVSCodewiththe.NETSDKasthefoundation.Next,useNuGetpackageslikeMath.NETNumericsforlinearalgebr

Choosing the Right C# Collection Type for Performance Choosing the Right C# Collection Type for Performance Aug 01, 2025 am 03:47 AM

Choosing the right collection type can significantly improve C# program performance. 1. Frequently insert or delete the LinkedList in the middle, 2. Quickly search using HashSet or Dictionary, 3. Fixed element count to use arrays first, 4. Select HashSet when unique values are required, 5. Frequently searching using Dictionary or SortedDictionary, 6. Consider ConcurrentBag or ConcurrentDictionary in multi-threaded environment.

C# struct vs class performance comparison C# struct vs class performance comparison Aug 02, 2025 am 11:56 AM

structs are not necessarily faster, performance depends on the scenario. struct is the value type, assignment copy the entire structure, class is the reference type, assignment copy only the reference. The struct is usually allocated on the stack, and the fast but frequent passing of large structures will increase the replication overhead, and the class allocation involves GC pressure on the heap. Small structs are suitable for high-performance and cache-friendly scenarios, and large structs should be avoided or passed with ref/in. The compact memory of the struct array is conducive to caching, and the class array references are scattered to affect efficiency. Scenarios where struct are preferred: small data, short life cycle, no inheritance or virtual methods are required. Avoid using struct scenarios: large structure, complex logic, polymorphic, frequent packing, and sharing

What is the static keyword in C# used for? What is the static keyword in C# used for? Jul 30, 2025 am 02:24 AM

In C#, the static keyword is used to define members belonging to the type itself and can be accessed without instantiation. 1. Static variables are shared by all instances of the class and are suitable for tracking global state, such as recording the number of instantiation of the class; 2. Static methods belong to classes rather than objects, and cannot directly access non-static members, and are often used in helper functions in tool classes; 3. Static classes cannot be instantiated and only contain static members. They are suitable for organizing stateless practical methods, but cannot inherit or implement interfaces. When using it, you need to pay attention to memory management and thread safety issues.

Working with JSON and XML Serialization in C# Working with JSON and XML Serialization in C# Jul 31, 2025 am 04:12 AM

The choice of JSON or XML depends on the application scenario: 1. The situation of using JSON includes WebAPI return data, front-end interaction, modern service communication, and lightweight configuration; 2. The situation of using XML includes legacy system compatibility, namespace support, document-based data structures, and enterprise-level application interface specifications. In C#, .NETCore uses System.Text.Json for JSON serialization by default, with better performance and supports formatted output and null value retention; XML is implemented through XmlSerializer, suitable for old projects, and can customize tag names and namespaces, but does not support circular references, and needs to be processed manually or replaced with other libraries. Rationally select and configure serialization methods to help deal with different developments

Managing Memory Leaks and Garbage Collection in C# Managing Memory Leaks and Garbage Collection in C# Aug 02, 2025 am 04:24 AM

Memory leaks do exist and have a profound impact in C#, especially for long-term applications. Common signals include continuous memory rise and frequent GC but no obvious release. They can be analyzed and confirmed by tools such as VisualStudio and dotMemory. The main reasons and solutions are as follows: 1. Forgot to cancel the event subscription, you should manually cancel or use weak references; 2. The static collection is not cleaned, and the entry needs to be removed regularly or use WeakReference; 3. Unmanaged resources are not released, IDisposable should be implemented and using using statements. In addition, understanding the generational GC mechanism and optimizing memory usage such as reducing temporary object creation, rational use of structures, and avoiding LOH fragmentation can also help improve performance. Master this

See all articles