【问题标题】:Need some clarification with Stacks and Templates in C++ [closed]需要对 C++ 中的堆栈和模板进行一些说明 [关闭]
【发布时间】:2018-06-03 16:10:11
【问题描述】:

所以我有一个问题正在解决我的大学课程。本质上,教授在头文件和 main() 中给了我们一个模板,他问我们如果我们尝试“cout

#ifndef STACK_H
#define STACK_H
#include <vector>

using namespace std;

template <typename T>
class Stack
{
    vector<T> container;
public:
    Stack(): container() {}
    void push(T x) { container.push_back(x); }
    void pop() { if (container.size() > 0) container.pop_back(); }
    T top(){ if (container.size() > 0) return container.back(); }
    bool empty() { return container.empty(); }
};

#endif

这里是main():

#include <iostream>
#include <string>

#include "stack.h"

main()
{
Stack<int> s1;

s1.push(4);
s1.push(3);
s1.push(2);
s1.push(1);
while (!s1.empty()) {
    cout << s1.top() << endl;
    s1.pop();
}

Stack<string> s2;
s2.push("Yoda said ");
s2.push("something ");
s2.push("to write ");
while (!s2.empty()) {
    cout << s2.top();
    s2.pop();
}

s2.pop();
cout << s2.top();

cout << endl;

}

我知道我们会得到一个分段错误或类似的东西,因为我们试图访问或 pop() 一个空堆栈。他希望我们只更改 stack.h。我已经添加了:

"void pop() { if (container.size() > 0) container.pop_back(); }"

它适用于 s2.pop()。

我的问题是,当我尝试在该行中添加“if (container.size() > 0)”时:

"T top(){ return container.back(); }"

即使(至少我认为)我在返回之前检查了大小,我仍然会遇到分段错误?我将如何处理这个?在此先感谢:)

【问题讨论】:

    标签: c++ templates stack


    【解决方案1】:

    如果控制到达返回非 void 的函数的 },而不是到达 return,则行为未定义。任何事情都有可能发生。

    您必须将else 添加到.top(),并使用它来返回某种默认值(您可能想要return {};),或者抛出异常,或者阻止函数以其他方式返回.

    【讨论】:

    • 我不允许在主功能中编辑任何东西:(我只能编辑模板。
    • @Justin 我对main()什么都没说。我要求你编辑.top()
    【解决方案2】:

    你的

    s2.pop();
    cout << s2.top();
    

    在循环之外是 a) 在一个空容器上调用 pop()(很傻)。 b) 在空容器上调用top() 并使用结果; 错误

    当容器为空时,T top(){ if (container.size() &gt; 0) return container.back(); } 也会导致未定义的行为,此后该函数不会返回 T(它总是必须返回)。

    【讨论】:

    • 我知道他们在一个空容器上调用 pop() 和 top()。这就是他问我们的问题,哈哈。我们应该更改 stack.h 以避免这些错误。我的问题是为什么不会(如果 container.size() > 0) 为 T top(){ return container.back(); 工作}
    • @Justin 查看 HolyBlackCat 的回答以及我添加到自己的回答中的 UB 位。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 2019-04-03
    • 2016-06-16
    • 1970-01-01
    • 2016-03-24
    • 2014-10-02
    相关资源
    最近更新 更多