繁体   English   中英

如何构建带有成员函数的双端队列类? C ++

[英]How to construct a deque class w/ member functions in it? C++

我是C ++的新手,我的教授要求我们构造Deque类以及其他几个类,例如Stack和Queue。

以下是到目前为止我所做的。

我的问题是:如何构造/使函数起作用? 例如,您究竟如何在此处制作push_front(int)函数? (实际上不必使用模板,使用int完全可以。)

仅举一个例子就足以让我弄清楚下一步该怎么做。

真的很感谢帮助。

#ifndef CLASSES_H
#define CLASSES_H

#include <vector>
#include <iostream>
class Deque{
public:
    void push_front(int); //Insertion from left
    void push_back(int x){m_Vector.push_back(x);};//Insertion from right
    void pop_front();//Remove from left
    void pop_back(){m_Vector.pop_back();};//Remove from right
    int getL()const {return m_left;}
    int getR()const {return m_right;}
protected:
    //Protected Data members
    int m_left;
    int m_right;
    unsigned int size;
    unsigned int length;
    vector<int> m_Vector;
//structure  
};
// Deque member functions definitions


class Queue:private Deque{
public:
    void insertL(int a){push_front(a);};
    int removeR(){return pop_back();};
};

class Stack:private Deque{
public:
    void push(int x){push_front(x);};
    int pop(){return pop_front();};
    bool full(){return m_left == m_right;}
protected:
    using Deque::m_left;
    using Deque::m_right;
};


#endif /* CLASSES_H */

更新:

我只是做了一个这样的小功能,

void Deque::push_front(int x){
    m_Vector.insert(m_Vector.begin(),x);
}

我把它放在Deque课后。 有人可以告诉我我做得对吗?

第二次更新:

我像这样完成pop_front。

void Deque::pop_front(){
    m_Vector.front() = std::move(m_Vector.back());
    m_Vector.pop_back();
}

push_frontvector效率极低,通常应避免使用它。 (您必须移动向量的每个元素才能执行此操作)。

假设您有m_leftm_right我假设您的教授希望您在向量中创建一个循环缓冲区。 这根本不涉及push_back或任何类似的函数,因为实际数据值可能是整体值的子集,并且数据的正面和背面可以在任意索引处,而不必在vector的末尾。

但是,一旦实现了Deque的功能,您的StackQueue看起来就很好。

研究循环缓冲区是一个主题,在线上有大量的解释它们如何工作的,它们在单个操作的基础上可以有效地处理许多工作负载,但是它们在空间使用方面具有怪异的属性,并且访问成本更高,因此未在默认情况下提供向量。

我建议您花时间举例说明这4种方法,尤其是在边界条件方面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM