C/C++教程

c++之队列(Queue)

本文主要是介绍c++之队列(Queue),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

队列(Queue)与栈一样,是一种线性存储结构,它具有如下特点:

(1)队列中的数据元素遵循“先进先出”(First In First Out)的原则,简称FIFO结构;

(2)在队尾添加元素,在队头删除元素。

q.empty()     //      如果队列为空返回true,否则返回false
q.size()      //      返回队列中元素的个数
q.pop()       //      删除队列首元素但不返回其值
q.front()     //      返回队首元素的值,但不删除该元素
q.push()      //      在队尾压入新元素
q.back()      //      返回队列尾元素的值,但不删除该元素

class LRUCache {
public:
    LRUCache(int capacity) {
        max_capacity=capacity;
    }
    
    int get(int key) {
        if(memory.count(key)==1) {
            the_key.erase(key);
            the_key.push(key);
            return memory[key];
        }
        else return -1;
    }
    
    void put(int key, int value) {
        if(the_key.size()==max_capacity){
            int a=the_key.top;
            the_key.pop();
            the_key.push(key);
            memory.erase(a);
            memory[key]=value;
        }
        else{
            the_key.erase(key);
            the_key.push(key);
            memory[key]=value;
        }
    }
private:
    int max_capacity;
    unordered_map<int,int> memory;
    queue<int> the_key;
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */

O(1) 复杂度支持任意位置删除的 priority_queue 实现_努力中的老周的专栏-CSDN博客

这篇关于c++之队列(Queue)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!