简体   繁体   English

C ++自定义堆栈打印问题

[英]C++ Custom Stack Printing Issues

I am creating a custom class Stack to store a couple string variables. 我正在创建一个自定义类Stack来存储几个字符串变量。 When I attempt to print the stack, it says that the stack is always empty, which is not correct. 当我尝试打印纸叠时,它说纸叠总是空的,这是不正确的。 I am using vectors to represent the custom stack, so the way I go about my print method should work, but for some reason it does not. 我使用矢量来表示自定义堆栈,因此我的打印方法应该可以使用,但是由于某种原因,它不能使用。 What is my error? 我怎么了 Is it in my isEmpty method? 是在我的isEmpty方法中吗?

void stack::printStack() {

    std::vector<std::string> v;

    if(stack::isEmpty()) {

        std::cout << "Stack is empty! " << std::endl;
    }
    else {
        for(int i = 0; i != v.size(); i++) {
            std::cout << v[i] << std::endl;
        }
    }
}

You are returning a copy of the underlying vector with 您将返回具有以下内容的基础向量的副本

std::vector<std::string> stack::getVector();

This results in all calls such as stack::getVector().push_back(n); 这将导致所有调用,例如stack::getVector().push_back(n); making no modifications to the stack::v , but modifying the returned temporary instead. 不对stack::v进行任何修改,而是修改返回的临时文件。

I don't see, why you shouldn't be using v directly in the member functions: 我不明白,为什么您不应该直接在成员函数中使用v

v.push_back(n);

Or, if you don't want to do that (for some reason), make getVector return both reference-to-const and reference-to-non-const: 或者,如果您不想这样做(由于某种原因),请使getVector既返回对常量的引用又对非常量的引用:

std::vector<std::string> const& stack::getVector() const { return v; };
std::vector<std::string> &stack::getVector()             { return v; };

Note, that you're breaking encapsulation with std::vector<std::string> & returning overload. 请注意,您正在破坏std::vector<std::string> &封装并返回过载。

You are creating a local variable here: 您将在此处创建局部变量:

void stack::printStack(){

      std::vector<std::string> v;

That v is not the same as the v member variable. vv成员变量不同。 That local v is empty, thus your loop never prints. 该本地v为空,因此您的循环永远不会输出。

Also, use descriptive variable names. 另外,请使用描述性变量名。 Using a single letter variable name such as v is not a good idea. 使用单个字母变量名称(例如v )不是一个好主意。

Also, with respect to return a vector by reference or copy, see this question and answer: Returning vector copies. 另外,关于通过引用或副本返回矢量 ,请参阅以下问题和答案: 返回矢量副本。

So do you want to return a copy of the vector, or do you want to return the actual vector? 那么,您是否要返回向量的副本,还是要返回实际的向量? If it is the latter, return a reference, if it's the former, then return a copy (as your current code is doing). 如果是后者,则返回引用;如果是前者,则返回副本(如当前代码所做的那样)。 Note that there are implications in returning a copy as opposed to returning a reference (as the link shows). 请注意,与返回引用(如链接所示)相反,返回副本有一些含义。

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

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