【问题标题】:How to determine container type based on user input如何根据用户输入确定容器类型
【发布时间】:2019-09-13 21:16:45
【问题描述】:

对于我的一个学校项目,我正在实现一个包含两个独立容器的类,这些容器应该是堆栈或队列,具体取决于用户指定的容器。我的问题是,是否可以创建两个私有成员容器——我们称它们为 container1 和 container2——并指定每个容器分别是堆栈还是队列? (建设中)

【问题讨论】:

  • 这些是std::stackstd::queue吗?
  • 每个容器的类型是在编译时还是运行时确定的?
  • 是的,它来自标准语言
  • 我正在考虑使用双端队列来表示两者,并且只是实现可以与双端队列一起使用的函数,例如堆栈或队列,但我认为必须有更好的方法。
  • 使用单个 deque 并在后台更改界面的行为方式是一种更好的方法。

标签: c++ class data-structures


【解决方案1】:

使用模板,您可能有

template <typename Container1, typename Container2>
class MyClass
{
public:
    // ....
private:
    Container1 c1;
    Container2 c2;
};

// Dispatch functions for non uniform code
template <typename T> void do_job_specific(std::stack<T>& s) {/*..*/}
template <typename T> void do_job_specific(std::queue<T>& d) {/*..*/}

// Common code
template <typename Container> void do_job_common(Container& d) {/*..*/}

主要工作

template <typename T> // would be MyClass<C1, C2>
void do_job()
{
    T myClass;
    // ...
}

enum class EContainer { Stack, Queue};

void dispatch_job(EContainer e1, EContainer e2)
{
    using T1 = std::stack<int>;
    using T2 = std::queue<int>;
    if (e1 == EContainer::Stack) {
        if (e2 == EContainer::Stack)) {
            do_job<std::stack<T1, T1>>();
        } else {
            do_job<std::stack<T1, T2>>();
        }
    } else {
        if (e2 == EContainer::Stack)) {
            do_job<std::stack<T2, T1>>();
        } else {
            do_job<std::stack<T2, T2>>();
        }
    } 
}

现在main 只需使用来自用户的选定枚举调用方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 2020-07-02
    • 1970-01-01
    • 2022-08-03
    相关资源
    最近更新 更多